class DummyConfigWidget(QWidget, config.ConfigurationWidgetMixin): NAME_PREFIX = 'dummy' PROPERTY_MAP = dict(QCheckBox='checked', QLineEdit='text') CHANGED_SIGNAL_MAP = dict(QCheckBox='toggled', QLineEdit='textChanged') configurationChanged = pyqtSignal(bool) def __init__(self, config, parent=None): QWidget.__init__(self, parent) layout = QHBoxLayout(self) self.setLayout(layout) self.checkbox = QCheckBox(self) self.checkbox.setObjectName('dummy_checkbox') layout.addWidget(self.checkbox) self.lineedit = QLineEdit(self) self.lineedit.setObjectName('dummy_lineedit') layout.addWidget(self.lineedit) self._setup(config) def change(self, text, check_state): self.lineedit.setText(text) self.checkbox.setChecked(check_state) def check(self, text, check_state): __tracebackhide__ = True assert unicode(self.lineedit.text()) == text assert self.checkbox.isChecked() == check_state
def _init_ui(self): self.list_items = [] if self._columm == 2: self._box = QGridLayout() else: self._box = QVBoxLayout() j, i, x = 0, 0, 0 for item in self._list_apps: if self.objectName() != item.category.name: self.setObjectName(item.category.name) new_qcb = QCheckBox(item.title) new_qcb.setObjectName(item.name) new_qcb.clicked.connect(self._addcommand) if isinstance(self._box, QGridLayout): if i == 0: self._box.addWidget(new_qcb, j, i) i = 1 x += 1 else: self._box.addWidget(new_qcb, j, i) i = 0 x += 1 if x == 2: j += 1 x = 0 elif isinstance(self._box, QVBoxLayout): self._box.addWidget(new_qcb) self.setLayout(self._box)
def __init__(self, values=None): RangeDialog.__init__(self, 'Darkening law range') self.setFixedHeight(102) grid = QGridLayout() grid.setAlignment(Qt.AlignTop) grid.setColumnStretch(1, 1) self.checkboxes = [] row = 1 cell = 1 for item in DarkeningLaw.items: checkbox = QCheckBox(item[0]) checkbox.setObjectName(item[1]) checkbox.stateChanged.connect(self._on_checkbox_state_changed) grid.addWidget(checkbox, row, cell) self.checkboxes.append(checkbox) if values and item[1] in values: checkbox.setChecked(True) cell += 1 if cell > 2: cell = 1 row += 1 self.layout().insertLayout(0, grid) if not len(self.values()): self.ok_button.setDisabled(True)
def __init__(self, values=None): RangeDialog.__init__(self, 'Darkening law range') self.setFixedHeight(102) grid = QGridLayout() grid.setAlignment(Qt.AlignTop) grid.setColumnStretch(1,1) self.checkboxes = [] row = 1 cell = 1 for item in DarkeningLaw.items: checkbox = QCheckBox(item[0]) checkbox.setObjectName(item[1]) checkbox.stateChanged.connect(self._on_checkbox_state_changed) grid.addWidget(checkbox, row, cell) self.checkboxes.append(checkbox) if values and item[1] in values: checkbox.setChecked(True) cell += 1 if cell > 2: cell = 1 row += 1 self.layout().insertLayout(0, grid) if not len(self.values()): self.ok_button.setDisabled(True)
class Dialog(toly_dialog.ToLyDialog): def __init__(self, parent=None): self.imp_prgm = "midi2ly" self.userg = "midi_import" self.useAbsCheck = QCheckBox() self.impChecks = [self.useAbsCheck] self.useAbsCheck.setObjectName("absolute-mode") self.impExtra = [] super(Dialog, self).__init__(parent) app.translateUI(self) qutil.saveDialogSize(self, "midi_import/dialog/size", QSize(480, 260)) self.makeCommandLine() self.loadSettings() def translateUI(self): self.useAbsCheck.setText(_("Pitches in absolute mode")) self.buttons.button(QDialogButtonBox.Ok).setText(_("Run midi2ly")) super(Dialog, self).translateUI() def makeCommandLine(self): """Reads the widgets and builds a command line.""" cmd = ["$midi2ly"] if self.useAbsCheck.isChecked(): cmd.append('-a') cmd.append("$filename") self.commandLine.setText(' '.join(cmd)) def loadSettings(self): """Get users previous settings.""" self.imp_default = [False] self.settings = QSettings() self.settings.beginGroup('midi_import') super(Dialog, self).loadSettings() def saveSettings(self): """Save users last settings.""" self.settings = QSettings() self.settings.beginGroup('midi_import') super(Dialog, self).saveSettings()
def connect_features(self, source, target): """ Connects the source feature with the target feature. @param source: A QgsPointLocator.Match object. Its foreign key will be updated. A dialog will be opened which asks the user for which foreign key(s) he wants to update. @param target: A QgsPointLocator.Match object. This feature will be used as link target. Its obj_id attribute will be used as primary key. """ dlg = QDialog(self.iface.mainWindow()) dlg.setWindowTitle(self.tr('Select properties to connect')) dlg.setLayout(QFormLayout()) properties = list() for prop in self.network_element_sources[source.layer()]['fields']: cbx = QCheckBox(prop[1]) cbx.setObjectName(prop[0]) properties.append(cbx) dlg.layout().addWidget(cbx) btn_box = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) dlg.layout().addWidget(btn_box) btn_box.accepted.connect(dlg.accept) btn_box.rejected.connect(dlg.reject) source_feature = self.get_feature_for_match(source) target_feature = self.get_feature_for_match(target) if dlg.exec_(): for cbx in properties: if cbx.isChecked(): source_feature[cbx.objectName()] = target_feature['obj_id'] if source.layer().updateFeature(source_feature): self.iface.messageBar().pushMessage('QGEP', self.tr('Connected {} to {}').format( source_feature[ 'identifier'], target_feature['identifier']), QgsMessageBar.INFO, 5) else: self.iface.messageBar().pushMessage('QGEP', self.tr( 'Error connecting features'), QgsMessageBar.WARNING, 5) self.reset()
def connect_features(self, source, target): """ Connects the source feature with the target feature. @param source: A QgsPointLocator.Match object. Its foreign key will be updated. A dialog will be opened which asks the user for which foreign key(s) he wants to update. @param target: A QgsPointLocator.Match object. This feature will be used as link target. Its obj_id attribute will be used as primary key. """ dlg = QDialog(self.iface.mainWindow()) dlg.setWindowTitle(self.tr('Select properties to connect')) dlg.setLayout(QFormLayout()) properties = list() for prop in self.network_element_sources[source.layer()]: cbx = QCheckBox(prop[1]) cbx.setObjectName(prop[0]) properties.append(cbx) dlg.layout().addWidget(cbx) btn_box = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) dlg.layout().addWidget(btn_box) btn_box.accepted.connect(dlg.accept) btn_box.rejected.connect(dlg.reject) source_feature = self.get_feature_for_match(source) target_feature = self.get_feature_for_match(target) if dlg.exec_(): for cbx in properties: if cbx.isChecked(): source_feature[cbx.objectName()] = target_feature['obj_id'] if source.layer().updateFeature(source_feature): self.iface.messageBar().pushMessage('QGEP', self.tr('Connected {} to {}').format( source_feature[ 'identifier'], target_feature['identifier']), QgsMessageBar.INFO, 5) else: self.iface.messageBar().pushMessage('QGEP', self.tr( 'Error connecting features'), QgsMessageBar.WARNING, 5) self.reset()
class ChangeClassDialog(QDialog): pagetitle = 'Change Class' holdc = {} hold = [] def __init__(self, session, students, parent=None): super(ChangeClassDialog, self).__init__(parent) ko = 0 self.students = self.pullStudents(students) self.session = session[2] self.claszs = self.pullClass(1) self.d_displayData = QComboBox() for k in self.claszs: act = str(self.claszs[k]) + ' ' for k in self.claszs: arr = self.pullClass(k) for dd in arr: self.d_displayData.addItem(str(act + arr[dd]).upper(), dd) self.frame1 = QGroupBox('Students') self.frame2 = QGroupBox('New Class') hc1_box = QVBoxLayout() tree = QTreeWidget() tree.setHeaderLabel("Students?") self.std_arr = {} parent = QTreeWidgetItem(tree) parent.setText(0, "Selected Students") parent.setFlags(parent.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable) for student in self.students: child = QTreeWidgetItem(parent) child.setFlags(child.flags() | Qt.ItemIsUserCheckable) child.setText( 0, str(student['surname'] + ' ' + student['firstname'] + ' ' + student['othername']).title()) self.std_arr[student['id']] = child child.setCheckState(0, Qt.Checked) ko += 1 hc1_box.addWidget(tree) self.li1 = [] self.li1ID = [] exp = QLabel('Select Class') ses_name = str(session[1]) + ' ' + str(session[3]) ses = QLabel(ses_name) v_box = QHBoxLayout() v_box.addWidget(exp) v_box.addStretch() v_box.addWidget(self.d_displayData) hv_box = QVBoxLayout() hv_box.addWidget(ses) hv_box.addStretch() hv_box.addLayout(v_box) self.frame1.setLayout(hc1_box) #frame1.setFrameShape(QFrame.StyledPanel) self.frame2.setLayout(hv_box) #frame2.setFrameShape(QFrame.StyledPanel) h_box = QVBoxLayout() h_box.addWidget(self.frame2) h_box.addWidget(self.frame1) self.pb = QPushButton() self.pb.setObjectName("setclass") self.pb.setText("Set Class") self.pb1 = QPushButton() self.pb1.setObjectName("remclass") self.pb1.setText("Remove from Class") self.pb2 = QPushButton() self.pb2.setObjectName("Cancel") self.pb2.setText("Cancel") but_box = QHBoxLayout() but_box.addWidget(self.pb2) but_box.addWidget(self.pb1) but_box.addWidget(self.pb) main_box = QVBoxLayout() main_box.addLayout(h_box) main_box.addLayout(but_box) self.setLayout(main_box) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_remove()) self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_close()) self.setWindowTitle(self.pagetitle) def catItems(self, a, b): _a = a self.cas = self.pullCas(_a) self.li1 = [] self.li1ID = [] for rp in self.hold: self.hc2_box.removeWidget(rp) sip.delete(rp) self.hold = [] ko = 0 for ca in self.cas: num = ca['id'] self.li1ID.append(num) self.c1 = QCheckBox('cbx' + str(num)) self.c1.setText(str(ca['name']).upper()) self.c1.setObjectName("chkx" + str(num)) self.c1.setChecked(True) self.hc2_box.addWidget(self.c1) self.hold.append(self.c1) self.li1.append(self.c1) ko += 1 #self.hc2_box.show() def pullClasz(self): cn = Db() arr = cn.selectn('datas', '', '', {'pubID': 11}) return arr def pullClass(self, a): self.a = a cn = Db() students = cn.select('datas', '', '', {'subID': self.a, 'active': 0}) arr = {} for j in students: arr[j[0]] = j[2] return arr def pullStudents(self, a): cn = Db() arr = cn.selectStudents(a) return arr def pullCas(self, a): _a = a cn = Db() arr = cn.selectn('datas', '', '', {'subID': _a}) return arr def button_close(self): self.reject() def button_remove(self): students = self.getValues() session = self.session data = StudentTable() data.classRemoveStudent(session, students) self.accept() def button_click(self): students = self.getValue() moveclass = self.d_displayData.itemData( self.d_displayData.currentIndex()) session = self.session data = StudentTable() data.classMoveStudent(session, moveclass, students) self.accept() def getValue(self): k1 = [] for i in self.std_arr: if self.std_arr[i].checkState(0) == Qt.Checked: k1.append(i) return k1 def getValues(self): k1 = [] for i in self.std_arr: if self.std_arr[i].checkState(0) == Qt.Checked: k1.append(i) return k1 def pullSession(self, a): # select a file self.a = a g = Db() return g.select('session', '', 1, {'id': self.a})
class LoginForm(QMainWindow): def __init__(self, parent=None): super(LoginForm, self).__init__(parent) self.width, self.height = 800, 650 self.crear_interfaz(self.width, self.height) self.checkbox_rememberme.clicked.connect(self.remember_me) self.button_login.clicked.connect(self.logging) # self.div_create.setVisible(False) self.database = Database() """self.label_rememberme.mousePressEvent = self.do_remember def do_remember(self, event): # TDE FIXME: Create another remember_me method for remember me label self.remember_me(event) """ def loading(self): print "loading..." def logging(self): self.valid_fields() def valid_fields(self): username = self.username.text() password = self.password.text() if username == '': self.username.setFocus(True) elif password == '': self.password.setFocus(True) else: self.loading() self.username.setEnabled(False) self.password.setEnabled(False) print "Logging validation username" if self.database.login(username, password): print "Bienvenido %s" % username else: print "Datos incorrectos!" # return True in end of statement def anim_left(self): animation = QPropertyAnimation(self.label_icon, "geometry") animation.setDuration(250) animation.setStartValue(QRect(0, 0, 20, 20)) animation.setEndValue(QRect(20, 0, 20, 20)) animation.start() self.animation = animation def anim_right(self): animation = QPropertyAnimation(self.label_icon, "geometry") animation.setDuration(250) animation.setStartValue(QRect(20, 0, 20, 20)) animation.setEndValue(QRect(0, 0, 20, 20)) animation.start() self.animation = animation def remember_me(self): if self.checkbox_rememberme.isChecked(): self.anim_left() self.label_icon.setGeometry(20, 0, 20, 20) else: self.anim_right() self.label_icon.setGeometry(0, 0, 20, 20) def crear_interfaz(self, width, height): self.setMinimumSize(width, height) self.setMaximumSize(width, height) self.setWindowTitle('I n i c i a s e s i ó n | SN') self.setObjectName('login_form_window') self.container = QWidget(self) self.container.setMinimumSize(width, height) self.container.setMaximumSize(width, height) self.container.setObjectName('login_container') self.title = QLabel(self) self.title.setText('I N I C I A S E S I Ó N G R Á T I S') self.title.setGeometry(210, 130, 400, 40) self.title.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self.title.setObjectName('login_title') self.username = QLineEdit(self) self.username.setPlaceholderText('N O M B R E D E U S U A R I O') self.username.setGeometry(260, 230, 300, 40) self.username.setObjectName('login_username') self.username.setAcceptDrops(False) self.password = QLineEdit(self) self.password.setPlaceholderText('C O N T R A S E Ñ A') self.password.setGeometry(260, 290, 300, 40) self.password.setObjectName('login_password') self.password.setEchoMode(QLineEdit.Password) self.checkbox_rememberme = QCheckBox(self) self.checkbox_rememberme.setLayoutDirection(Qt.RightToLeft) self.checkbox_rememberme.setGeometry(260, 360, 40, 20) self.checkbox_rememberme.setObjectName("login_rememberme") self.checkbox_rememberme.setCursor(QCursor(Qt.PointingHandCursor)) self.label_icon = QLabel(self.checkbox_rememberme) self.label_icon.setGeometry(0, 0, 20, 20) self.label_icon.setObjectName("label_icon") self.label_rememberme = QLabel(self) self.label_rememberme.setText("R E C U É R D A M E") self.label_rememberme.setGeometry(310, 360, 165, 20) self.label_rememberme.setObjectName("label_rememberme") self.button_login = QPushButton(self) self.button_login.setGeometry(315, 420, 200, 40) self.button_login.setText("I N I C I A R S E S I Ó N") self.button_login.setObjectName("button_login") self.layout = QGridLayout(self.container)
class PsychomotoCaDialog(QDialog): pagetitle = 'Skill-Assessment' holdc = {} hold = [] def __init__(self, parent=None): super(PsychomotoCaDialog, self).__init__(parent) ko = 0 self.subjects = self.pullSubjects() self.frame1 = QGroupBox('Skills') self.frame2 = QGroupBox('Categories') hc1_box = QVBoxLayout() hc2_box = QVBoxLayout() self.li = [] self.liID = [] for subject in self.subjects: num = subject['id'] self.liID.append(num) self.c = QRadioButton('cb' + str(num)) self.c.setText(str(subject['name']).upper()) self.c.setObjectName("chk" + str(num)) self.c.setChecked(False) self.c.toggled.connect( lambda state, x=num, y=self.c: self.catItems(x, y)) hc1_box.addWidget(self.c) self.li.append(self.c) ko += 1 self.li1 = [] self.li1ID = [] self.hc2_box = QVBoxLayout() self.frame1.setLayout(hc1_box) #frame1.setFrameShape(QFrame.StyledPanel) self.frame2.setLayout(self.hc2_box) #frame2.setFrameShape(QFrame.StyledPanel) h_box = QHBoxLayout() h_box.addWidget(self.frame1) h_box.addWidget(self.frame2) self.pb = QPushButton() self.pb.setObjectName("MakeEntries") self.pb.setText("Edit View") self.pb1 = QPushButton() self.pb1.setObjectName("View Report") self.pb1.setText("Report View") self.pb2 = QPushButton() self.pb2.setObjectName("Cancel") self.pb2.setText("Cancel") but_box = QHBoxLayout() but_box.addWidget(self.pb2) but_box.addWidget(self.pb1) but_box.addWidget(self.pb) main_box = QVBoxLayout() main_box.addLayout(h_box) main_box.addLayout(but_box) self.setLayout(main_box) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_close()) self.setWindowTitle(self.pagetitle) def catItems(self, a, b): _a = a self.cas = self.pullCas(_a) print(self.hold) self.li1 = [] self.li1ID = [] for rp in self.hold: self.hc2_box.removeWidget(rp) sip.delete(rp) self.hold = [] ko = 0 for ca in self.cas: num = ca['id'] self.li1ID.append(num) self.c1 = QCheckBox('cbx' + str(num)) self.c1.setText(str(ca['name']).upper()) self.c1.setObjectName("chkx" + str(num)) self.c1.setChecked(True) self.hc2_box.addWidget(self.c1) self.hold.append(self.c1) self.li1.append(self.c1) ko += 1 #self.hc2_box.show() def pullSubjects(self): cn = Db() arr = cn.selectn('datas', '', '', {'pubID': 9}) return arr def pullCas(self, a): _a = a cn = Db() arr = cn.selectn('datas', '', '', {'subID': _a}) return arr def button_close(self): self.reject() def button_click(self): self.accept() def getValue(self): k1 = [] k2 = [] for s in range(0, len(self.li)): if self.li[s].isChecked(): k1.append(self.liID[s]) else: k2.append(self.liID[s]) k11 = [] k21 = [] for s in range(0, len(self.li1)): if self.li1[s].isChecked(): k11.append(self.li1ID[s]) else: k21.append(self.li1ID[s]) return [k1, k11]
class PlayConfigTab( QWidget): """Display Config tab""" def __init__(self, parent): super(PlayConfigTab, self).__init__(parent) self.setupUi() def setupUi(self): """layout the window""" self.setContentsMargins(0, 0, 0, 0) vlayout = QVBoxLayout(self) vlayout.setContentsMargins(0, 0, 0, 0) sliderLayout = QHBoxLayout() self.kcfg_showShadows = QCheckBox(m18n('Show tile shadows'), self) self.kcfg_showShadows.setObjectName('kcfg_showShadows') self.kcfg_rearrangeMelds = QCheckBox(m18n('Rearrange undisclosed tiles to melds'), self) self.kcfg_rearrangeMelds.setObjectName('kcfg_rearrangeMelds') self.kcfg_showOnlyPossibleActions = QCheckBox(m18n('Show only possible actions')) self.kcfg_showOnlyPossibleActions.setObjectName('kcfg_showOnlyPossibleActions') self.kcfg_propose = QCheckBox(m18n('Propose what to do')) self.kcfg_propose.setObjectName('kcfg_propose') self.kcfg_animationSpeed = QSlider(self) self.kcfg_animationSpeed.setObjectName('kcfg_animationSpeed') self.kcfg_animationSpeed.setOrientation(Qt.Horizontal) self.kcfg_animationSpeed.setSingleStep(1) lblSpeed = QLabel(m18n('Animation speed:')) lblSpeed.setBuddy(self.kcfg_animationSpeed) sliderLayout.addWidget(lblSpeed) sliderLayout.addWidget(self.kcfg_animationSpeed) self.kcfg_useSounds = QCheckBox(m18n('Use sounds if available'), self) self.kcfg_useSounds.setObjectName('kcfg_useSounds') self.kcfg_uploadVoice = QCheckBox(m18n('Let others hear my voice'), self) self.kcfg_uploadVoice.setObjectName('kcfg_uploadVoice') pol = QSizePolicy() pol.setHorizontalPolicy(QSizePolicy.Expanding) pol.setVerticalPolicy(QSizePolicy.Expanding) spacerItem = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding) vlayout.addWidget(self.kcfg_showShadows) vlayout.addWidget(self.kcfg_rearrangeMelds) vlayout.addWidget(self.kcfg_showOnlyPossibleActions) vlayout.addWidget(self.kcfg_propose) vlayout.addWidget(self.kcfg_useSounds) vlayout.addWidget(self.kcfg_uploadVoice) vlayout.addLayout(sliderLayout) vlayout.addItem(spacerItem) self.setSizePolicy(pol) self.retranslateUi() def retranslateUi(self): """translate to current language""" pass
class ProxyPreferencesWidget(QDialog): def __init__(self, parent=None): super(ProxyPreferencesWidget, self).__init__(parent, Qt.Dialog) self.setObjectName('Dialog') self.resize(325, 142) self.setMinimumSize(QSize(325, 142)) self.setMaximumSize(QSize(325, 142)) self.formLayout = QFormLayout(self) self.formLayout.setObjectName('formLayout') self.proxyEnable = QCheckBox(self) self.proxyEnable.setObjectName('proxyEnable') self.proxyEnable.stateChanged.connect(self.enable_edit) self.formLayout.setWidget(0, QFormLayout.LabelRole, self.proxyEnable) self.proxyServer = QLineEdit(self) self.proxyServer.setObjectName('proxyServer') self.formLayout.setWidget(1, QFormLayout.FieldRole, self.proxyServer) self.proxyLogin = QLineEdit(self) self.proxyLogin.setObjectName('proxyLogin') self.formLayout.setWidget(2, QFormLayout.FieldRole, self.proxyLogin) #self.proxyPass = QLineEdit(self) plug_path = os.path.abspath(__file__) plug_path = os.path.dirname(plug_path) self.proxyPass = ButtonInLineEdit(self, plug_path + '/eye.svg') self.proxyPass.setObjectName('proxyPass') self.proxyPass.setEchoMode(QLineEdit.Password) self.formLayout.setWidget(3, QFormLayout.FieldRole, self.proxyPass) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.buttonBox.setObjectName('buttonBox') self.formLayout.setWidget(4, QFormLayout.FieldRole, self.buttonBox) self.label = QLabel(self) self.label.setObjectName('label') self.formLayout.setWidget(1, QFormLayout.LabelRole, self.label) self.label_2 = QLabel(self) self.label_2.setObjectName('label_2') self.formLayout.setWidget(2, QFormLayout.LabelRole, self.label_2) self.label_3 = QLabel(self) self.label_3.setObjectName('label_3') self.formLayout.setWidget(3, QFormLayout.LabelRole, self.label_3) self.setWindowTitle('Proxy preferences') self.proxyEnable.setText('Enable Proxy') self.label.setText('Proxy server:port') self.label_2.setText('Login') self.label_3.setText('Password') QObject.connect(self.buttonBox, SIGNAL('accepted()'), self.save_settings) QObject.connect(self.buttonBox, SIGNAL('rejected()'), self.reject) QObject.connect(self.proxyPass.Button, SIGNAL('pressed()'), lambda: self.proxyPass.setEchoMode(QLineEdit.Normal)) QObject.connect(self.proxyPass.Button, SIGNAL('released()'), lambda: self.proxyPass.setEchoMode(QLineEdit.Password)) QMetaObject.connectSlotsByName(self) def show_pass(self): self.proxyPass.setEchoMode(QLineEdit.Normal) def enable_edit(self): if not self.proxyEnable.isChecked(): self.proxyServer.setEnabled(False) self.proxyLogin.setEnabled(False) self.proxyPass.setEnabled(False) else: self.proxyServer.setEnabled(True) self.proxyLogin.setEnabled(True) self.proxyPass.setEnabled(True) def set_values(self, preferences): self.proxyEnable.setChecked(preferences['proxy_enabled']) self.proxyServer.setText(preferences['proxy_server']) self.proxyLogin.setText(preferences['proxy_login']) self.proxyPass.setText(preferences['proxy_password']) self.enable_edit() def save_settings(self): qsettings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat) qsettings.beginGroup('proxy') qsettings.setValue('enabled', self.proxyEnable.isChecked()) qsettings.setValue('server', self.proxyServer.text()) qsettings.setValue('login', self.proxyLogin.text()) qsettings.setValue('password', base64.b64encode(self.proxyPass.text())) qsettings.endGroup() self.accept()
class ToLyDialog(QDialog): def __init__(self, parent=None): super(ToLyDialog, self).__init__(parent) self._info = None self._document = None self._path = None mainLayout = QGridLayout() self.setLayout(mainLayout) tabs = QTabWidget() import_tab = QWidget() post_tab = QWidget() itabLayout = QGridLayout(import_tab) ptabLayout = QGridLayout(post_tab) tabs.addTab(import_tab, self.imp_prgm) tabs.addTab(post_tab, "after import") self.formatCheck = QCheckBox() self.trimDurCheck = QCheckBox() self.removeScalesCheck = QCheckBox() self.runEngraverCheck = QCheckBox() self.postChecks = [self.formatCheck, self.trimDurCheck, self.removeScalesCheck, self.runEngraverCheck] self.versionLabel = QLabel() self.lilyChooser = lilychooser.LilyChooser() self.commandLineLabel = QLabel() self.commandLine = QTextEdit(acceptRichText=False) self.formatCheck.setObjectName("reformat") self.trimDurCheck.setObjectName("trim-durations") self.removeScalesCheck.setObjectName("remove-scaling") self.runEngraverCheck.setObjectName("engrave-directly") self.buttons = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) userguide.addButton(self.buttons, self.userg) row = 0 for r, w in enumerate(self.impChecks): row += r itabLayout.addWidget(w, row, 0, 1, 2) w.toggled.connect(self.makeCommandLine) row += 1 for r, w in enumerate(self.impExtra): row += r itabLayout.addWidget(w, row, 0, 1, 2) itabLayout.addWidget(widgets.Separator(), row + 1, 0, 1, 2) itabLayout.addWidget(self.versionLabel, row + 2, 0, 1, 0) itabLayout.addWidget(self.lilyChooser, row + 3, 0, 1, 2) itabLayout.addWidget(widgets.Separator(), row + 4, 0, 1, 2) itabLayout.addWidget(self.commandLineLabel, row + 5, 0, 1, 2) itabLayout.addWidget(self.commandLine, row + 6, 0, 1, 2) ptabLayout.addWidget(self.formatCheck, 0, 0, 1, 2) ptabLayout.addWidget(self.trimDurCheck, 1, 0, 1, 2) ptabLayout.addWidget(self.removeScalesCheck, 2, 0, 1, 2) ptabLayout.addWidget(self.runEngraverCheck, 3, 0, 1, 2) ptabLayout.setRowStretch(4, 10) mainLayout.addWidget(tabs, 0, 0, 9, 2) mainLayout.addWidget(self.buttons, 10, 0, 1, 2) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) self.lilyChooser.currentIndexChanged.connect(self.slotLilyPondVersionChanged) self.slotLilyPondVersionChanged() def translateUI(self): self.versionLabel.setText(_("LilyPond version:")) self.commandLineLabel.setText(_("Command line:")) self.formatCheck.setText(_("Reformat source")) self.trimDurCheck.setText(_("Trim durations (Make implicit per line)")) self.removeScalesCheck.setText(_("Remove fraction duration scaling")) self.runEngraverCheck.setText(_("Engrave directly")) def setDocument(self, path): """Set the full path to the MusicXML document.""" self._document = path def slotLilyPondVersionChanged(self): self._info = self.lilyChooser.lilyPondInfo() def getCmd(self, outputname='-'): """Returns the command line.""" cmd = [] for t in self.commandLine.toPlainText().split(): if t == '$musicxml2ly': cmd.extend(self._info.toolcommand('musicxml2ly')) elif t == '$midi2ly': cmd.extend(self._info.toolcommand('midi2ly')) elif t == '$abc2ly': cmd.extend(self._info.toolcommand('abc2ly')) elif t == '$filename': cmd.append(self._document) else: cmd.append(t) cmd.extend(['--output', outputname]) return cmd def run_command(self): """Run command line.""" cmd = self.getCmd() directory = os.path.dirname(self._document) subenviron = None if os.name == "nt": # Python 2.7 subprocess on Windows chokes on unicode in env subenviron = util.bytes_environ() else: subenviron = dict(os.environ) if sys.platform.startswith('darwin'): try: del subenviron['PYTHONHOME'] except KeyError: pass try: del subenviron['PYTHONPATH'] except KeyError: pass proc = subprocess.Popen(cmd, cwd=directory, env = subenviron, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE) stdouterr = proc.communicate() return stdouterr def getPostSettings(self): """Returns settings in the post import tab.""" post = [] for p in self.postChecks: post.append(p.isChecked()) return post def loadSettings(self): """Get users previous settings.""" post_default = [True, False, False, True] for i, d in zip(self.impChecks, self.imp_default): i.setChecked(self.settings.value(i.objectName(), d, bool)) for p, f in zip(self.postChecks, post_default): p.setChecked(self.settings.value(p.objectName(), f, bool)) def saveSettings(self): """Save users last settings.""" for i in self.impChecks: self.settings.setValue(i.objectName(), i.isChecked()) for p in self.postChecks: self.settings.setValue(p.objectName(), p.isChecked())
class GuiMain(object): def __init__(self, data): self.data = data self.loadSave = False def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") #Set size of window and make it non-resizeable MainWindow.resize(818, 665) MainWindow.setFixedHeight(665) MainWindow.setFixedWidth(818) MainWindow.setWindowTitle("Map Master: Search for the Lost City") MainWindow.setWindowIcon(QIcon("icon_medium.ico")) #Set window backgrounds self.background = QLabel(MainWindow) self.backgroundPixmapMenu = QPixmap(normpath("images/gameMenu2.png")) self.backgroundPixmapSettings = QPixmap(normpath("images/gameMenuSettings2.png")) self.background.setPixmap(self.backgroundPixmapMenu) self.background.setGeometry(QtCore.QRect(0, 0, 818, 665)) #Stylesheet settings for labels and buttons self.fg = "QLabel {color:black}" self.fgb = "QPushButton {color:black}" self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.stackedWidget = QStackedWidget(self.centralwidget) self.stackedWidget.setEnabled(True) self.stackedWidget.setObjectName("stackedWidget") #Main Menu page self.menuPage = QWidget() self.menuPage.setObjectName("menuPage") self.startButton = QPushButton(self.menuPage) self.startButton.setStyleSheet(self.fgb) self.startButton.setGeometry(QtCore.QRect(600, 200, 180, 60)) self.startButton.setText(QApplication.translate("MainWindow", "Start Game", None, QApplication.UnicodeUTF8)) self.startButton.setObjectName("startButton") self.loadButton = QPushButton(self.menuPage) self.loadButton.setStyleSheet(self.fgb) self.loadButton.setGeometry(QtCore.QRect(600, 280, 180, 60)) self.loadButton.setText(QApplication.translate("MainWindow", "Load Game", None, QApplication.UnicodeUTF8)) self.loadButton.setObjectName("loadButton") self.settingsButton = QPushButton(self.menuPage) self.settingsButton.setStyleSheet(self.fgb) self.settingsButton.setGeometry(QtCore.QRect(600, 440, 180, 60)) self.settingsButton.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8)) self.settingsButton.setObjectName("settingsButton") self.quitButton = QPushButton(self.menuPage) self.quitButton.setStyleSheet(self.fgb) self.quitButton.setGeometry(QtCore.QRect(600, 520, 180, 60)) self.quitButton.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8)) self.quitButton.setObjectName("quitButton") self.instrButton = QPushButton(self.menuPage) self.instrButton.setStyleSheet(self.fgb) self.instrButton.setGeometry(QtCore.QRect(600, 360, 180, 60)) self.instrButton.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8)) self.instrButton.setObjectName("instrButton") self.stackedWidget.addWidget(self.menuPage) #Settings page self.settingsPage = QWidget() self.settingsPage.setObjectName("settingsPage") self.volumeSlider = QSlider(self.settingsPage) self.volumeSlider.setGeometry(QtCore.QRect(200, 200, 400, 30)) self.volumeSlider.setProperty("value", 50) self.volumeSlider.setOrientation(QtCore.Qt.Horizontal) self.volumeSlider.setObjectName("volumeSlider") self.soundLabel = QLabel(self.settingsPage) self.soundLabel.setGeometry(QtCore.QRect(340, 160, 120, 30)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(20) self.soundLabel.setFont(font) self.soundLabel.setStyleSheet(self.fg) self.soundLabel.setText(QApplication.translate("MainWindow", "Volume", None, QApplication.UnicodeUTF8)) self.soundLabel.setAlignment(QtCore.Qt.AlignCenter) self.soundLabel.setObjectName("soundLabel") #Quiet Sound Graphic self.quietGraphic = QLabel(self.settingsPage) self.quietGraphic.setPixmap(QPixmap(normpath("images/speakerQuiet.png"))) self.quietGraphic.setGeometry(QtCore.QRect(90, 180, 80, 80)) self.quietGraphic.setObjectName("quietGraphic") #Loud Sound Graphic self.loudGraphic = QLabel(self.settingsPage) self.loudGraphic.setPixmap(QPixmap(normpath("images/speakerLoud.png"))) self.loudGraphic.setEnabled(True) self.loudGraphic.setGeometry(QtCore.QRect(630, 180, 80, 80)) self.loudGraphic.setObjectName("loudGraphic") self.settingsLabel = QLabel(self.settingsPage) self.settingsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(36) self.settingsLabel.setFont(font) self.settingsLabel.setStyleSheet(self.fg) self.settingsLabel.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8)) self.settingsLabel.setAlignment(QtCore.Qt.AlignCenter) self.settingsLabel.setObjectName("settingsLabel") self.doneButton = QPushButton(self.settingsPage) self.doneButton.setStyleSheet(self.fgb) self.doneButton.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.doneButton.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8)) self.doneButton.setObjectName("doneButton") self.stackedWidget.addWidget(self.settingsPage) self.soundManager = Sounds(self.volumeSlider.sliderPosition()) #Main Game page self.mainPage = QWidget() self.mainPage.setObjectName("mainPage") #Person View self.personView = ViewGraphics(self.mainPage) self.personView.setGeometry(QtCore.QRect(0, 0, 390, 500)) self.personView.setObjectName("personView") #Map View self.mapView = ViewGraphics(self.mainPage) self.mapView.setGeometry(QtCore.QRect(410, 0, 390, 500)) self.mapView.setObjectName("mapView") #ClueView self.clueView = QLabel(self.mainPage) self.clueView.setGeometry(QtCore.QRect(0, 510, 390, 91)) self.clueView.setObjectName("clueView") font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(20) self.clueView.setFont(font) self.clueView.setStyleSheet(self.fg) #Map Toggles self.latLongCheck = QCheckBox(self.mainPage) self.latLongCheck.setGeometry(QtCore.QRect(420, 510, 97, 41)) self.latLongCheck.setText(QApplication.translate("MainWindow", "Latitude/ \n" "Longitude", None, QApplication.UnicodeUTF8)) self.latLongCheck.setObjectName("latLongCheck") self.colorCheck = QCheckBox(self.mainPage) self.colorCheck.setGeometry(QtCore.QRect(560, 510, 97, 41)) self.colorCheck.setText(QApplication.translate("MainWindow", "Color\n" "Coding", None, QApplication.UnicodeUTF8)) self.colorCheck.setObjectName("colorCheck") self.legendCheck = QCheckBox(self.mainPage) self.legendCheck.setGeometry(QtCore.QRect(680, 520, 97, 22)) self.legendCheck.setText(QApplication.translate("MainWindow", "Legend", None, QApplication.UnicodeUTF8)) self.legendCheck.setObjectName("legendCheck") self.searchButton = QPushButton(self.mainPage) self.searchButton.setStyleSheet(self.fgb) self.searchButton.setGeometry(QtCore.QRect(420, 560, 211, 41)) self.searchButton.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8)) self.searchButton.setObjectName("searchButton") #Score pieces self.scoreBox = QLabel(self.mainPage) self.scoreBox.setStyleSheet(self.fg) self.scoreBox.setGeometry(QtCore.QRect(720, 560, 71, 41)) self.scoreBox.setObjectName("scoreBox") self.scoreBox.setText(QApplication.translate("MainWindow", "0", None, QApplication.UnicodeUTF8)) self.scoreLabel = QLabel(self.mainPage) self.scoreLabel.setStyleSheet(self.fg) self.scoreLabel.setGeometry(QtCore.QRect(660, 570, 51, 17)) self.scoreLabel.setText(QApplication.translate("MainWindow", "Score:", None, QApplication.UnicodeUTF8)) self.scoreLabel.setAlignment(QtCore.Qt.AlignCenter) self.scoreLabel.setObjectName("scoreLabel") self.stackedWidget.addWidget(self.mainPage) #Help page self.helpPage = QWidget() self.helpPage.setObjectName("helpPage") self.HelpLabel = QLabel(self.helpPage) self.HelpLabel.setStyleSheet(self.fg) self.HelpLabel.setGeometry(QtCore.QRect(260, 30, 280, 60)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(36) self.HelpLabel.setFont(font) self.HelpLabel.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8)) self.HelpLabel.setAlignment(QtCore.Qt.AlignCenter) self.HelpLabel.setObjectName("HelpLabel") self.wInstr = QLabel(self.helpPage) self.wInstr.setStyleSheet(self.fg) self.wInstr.setGeometry(QtCore.QRect(200, 150, 40, 30)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(20) self.wInstr.setFont(font) self.wInstr.setText(QApplication.translate("MainWindow", "W", None, QApplication.UnicodeUTF8)) self.wInstr.setAlignment(QtCore.Qt.AlignCenter) self.wInstr.setObjectName("wInstr") self.sInstr = QLabel(self.helpPage) self.sInstr.setStyleSheet(self.fg) self.sInstr.setGeometry(QtCore.QRect(200, 200, 40, 30)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(20) self.sInstr.setFont(font) self.sInstr.setText(QApplication.translate("MainWindow", "S", None, QApplication.UnicodeUTF8)) self.sInstr.setAlignment(QtCore.Qt.AlignCenter) self.sInstr.setObjectName("sInstr") self.aInstr = QLabel(self.helpPage) self.aInstr.setStyleSheet(self.fg) self.aInstr.setGeometry(QtCore.QRect(200, 250, 40, 30)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(20) self.aInstr.setFont(font) self.aInstr.setText(QApplication.translate("MainWindow", "A", None, QApplication.UnicodeUTF8)) self.aInstr.setAlignment(QtCore.Qt.AlignCenter) self.aInstr.setObjectName("aInstr") self.dInstr = QLabel(self.helpPage) self.dInstr.setStyleSheet(self.fg) self.dInstr.setGeometry(QtCore.QRect(200, 300, 40, 30)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(20) self.dInstr.setFont(font) self.dInstr.setText(QApplication.translate("MainWindow", "D", None, QApplication.UnicodeUTF8)) self.dInstr.setAlignment(QtCore.Qt.AlignCenter) self.dInstr.setObjectName("dInstr") self.wInstr2 = QLabel(self.helpPage) self.wInstr2.setStyleSheet(self.fg) self.wInstr2.setGeometry(QtCore.QRect(400, 150, 180, 30)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(20) self.wInstr2.setFont(font) self.wInstr2.setText(QApplication.translate("MainWindow", "Move North", None, QApplication.UnicodeUTF8)) self.wInstr2.setAlignment(QtCore.Qt.AlignCenter) self.wInstr2.setObjectName("wInstr2") self.sInstr2 = QLabel(self.helpPage) self.sInstr2.setStyleSheet(self.fg) self.sInstr2.setGeometry(QtCore.QRect(400, 200, 180, 30)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(20) self.sInstr2.setFont(font) self.sInstr2.setText(QApplication.translate("MainWindow", "Move South", None, QApplication.UnicodeUTF8)) self.sInstr2.setAlignment(QtCore.Qt.AlignCenter) self.sInstr2.setObjectName("sInstr2") self.aInstr2 = QLabel(self.helpPage) self.aInstr2.setStyleSheet(self.fg) self.aInstr2.setGeometry(QtCore.QRect(400, 250, 180, 30)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(20) self.aInstr2.setFont(font) self.aInstr2.setText(QApplication.translate("MainWindow", "Move West", None, QApplication.UnicodeUTF8)) self.aInstr2.setAlignment(QtCore.Qt.AlignCenter) self.aInstr2.setObjectName("aInstr2") self.dInstr2 = QLabel(self.helpPage) self.dInstr2.setStyleSheet(self.fg) self.dInstr2.setGeometry(QtCore.QRect(400, 300, 180, 30)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(20) self.dInstr2.setFont(font) self.dInstr2.setText(QApplication.translate("MainWindow", "Move East", None, QApplication.UnicodeUTF8)) self.dInstr2.setAlignment(QtCore.Qt.AlignCenter) self.dInstr2.setObjectName("dInstr2") self.searchInstr = QPushButton(self.helpPage) self.searchInstr.setStyleSheet(self.fgb) self.searchInstr.setEnabled(True) self.searchInstr.setGeometry(QtCore.QRect(170, 350, 100, 30)) self.searchInstr.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8)) self.searchInstr.setAutoDefault(False) self.searchInstr.setDefault(False) self.searchInstr.setFlat(False) self.searchInstr.setObjectName("searchInstr") self.dInstr2_2 = QLabel(self.helpPage) self.dInstr2_2.setStyleSheet(self.fg) self.dInstr2_2.setGeometry(QtCore.QRect(380, 350, 211, 30)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(20) self.dInstr2_2.setFont(font) self.dInstr2_2.setText(QApplication.translate("MainWindow", "Search for clues", None, QApplication.UnicodeUTF8)) self.dInstr2_2.setAlignment(QtCore.Qt.AlignCenter) self.dInstr2_2.setObjectName("dInstr2_2") self.doneButton2 = QPushButton(self.helpPage) self.doneButton2.setStyleSheet(self.fgb) self.doneButton2.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.doneButton2.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8)) self.doneButton2.setObjectName("doneButton2") self.stackedWidget.addWidget(self.helpPage) #Credits page self.creditsPage = QWidget() self.creditsPage.setObjectName("creditsPage") self.creditsLabel = QLabel(self.creditsPage) self.creditsLabel.setStyleSheet(self.fg) self.creditsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(36) self.creditsLabel.setFont(font) self.creditsLabel.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8)) self.creditsLabel.setAlignment(QtCore.Qt.AlignCenter) self.creditsLabel.setObjectName("creditsLabel") self.credits = QLabel(self.creditsPage) self.credits.setStyleSheet(self.fg) self.credits.setGeometry(QtCore.QRect(180, 150, 500, 400)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(20) self.credits.setFont(font) self.credits.setText(QApplication.translate("MainWindow", "Gary Lent\n" "Grant Stafford\n" "Jessie Liu\n" "Peter Andrien\n" "Nokia (Qt4 framework)\n" "Riverbank Computing Ltd (PyQt)\n" "Celestial Aeon Project", None, QApplication.UnicodeUTF8)) self.credits.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.credits.setObjectName("credits") self.doneButton3 = QPushButton(self.creditsPage) self.doneButton3.setStyleSheet(self.fgb) self.doneButton3.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.doneButton3.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8)) self.doneButton3.setObjectName("doneButton3") self.stackedWidget.addWidget(self.creditsPage) #Story page self.storyPage = QWidget() self.storyPage.setObjectName("storyPage") self.storyLabel = QLabel(self.storyPage) self.storyLabel.setStyleSheet(self.fg) self.storyLabel.setGeometry(QtCore.QRect(100, 50, 600, 400)) font = QFont() font.setFamily("Century Schoolbook L") font.setPointSize(25) self.storyLabel.setFont(font) self.storyLabel.setText(QApplication.translate("MainWindow", "My name is Travis Sinclair.\n I'm a skilled cartographer.\n I recently lost my job, but stumbled\n on a clue that may change my life \nforever. I've set off on a quest - a quest\n to find a lost city. I've found a clue,\n and believe there may be more.\n Help me find the lost city. ", None, QApplication.UnicodeUTF8)) self.storyLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.storyLabel.setObjectName("storyLabel") self.nextButton = QPushButton(self.storyPage) self.nextButton.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.nextButton.setText(QApplication.translate("MainWindow", "Next", None, QApplication.UnicodeUTF8)) self.nextButton.setObjectName("nextButton") self.stackedWidget.addWidget(self.storyPage) self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) #Menu bar self.menubar = QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 818, 25)) self.menubar.setObjectName("menubar") self.menuMenu = QMenu(self.menubar) self.menuMenu.setTitle(QApplication.translate("MainWindow", "Menu", None, QApplication.UnicodeUTF8)) self.menuMenu.setObjectName("menuMenu") MainWindow.setMenuBar(self.menubar) self.actionSave_Game = QAction(MainWindow) self.actionSave_Game.setText(QApplication.translate("MainWindow", "Save Game", None, QApplication.UnicodeUTF8)) self.actionSave_Game.setObjectName("actionSave_Game") self.actionCredits = QAction(MainWindow) self.actionCredits.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8)) self.actionCredits.setObjectName("actionCredits") self.actionQuit = QAction(MainWindow) self.actionQuit.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8)) self.actionQuit.setObjectName("actionQuit") self.actionSettings = QAction(MainWindow) self.actionSettings.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8)) self.actionSettings.setObjectName("actionSettings") self.actionHelp = QAction(MainWindow) self.actionHelp.setText(QApplication.translate("MainWindow", "Help", None, QApplication.UnicodeUTF8)) self.actionHelp.setObjectName("actionHelp") self.actionMain_Menu = QAction(MainWindow) self.actionMain_Menu.setText(QApplication.translate("MainWindow", "Main Menu", None, QApplication.UnicodeUTF8)) self.actionMain_Menu.setObjectName("actionMain_Menu") self.menuMenu.addAction(self.actionSettings) self.menuMenu.addAction(self.actionHelp) self.menuMenu.addAction(self.actionSave_Game) self.menuMenu.addAction(self.actionCredits) self.menuMenu.addAction(self.actionMain_Menu) self.menuMenu.addAction(self.actionQuit) self.menubar.addAction(self.menuMenu.menuAction()) self.retranslateUi(MainWindow) self.stackedWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) #These are the slots and signals to connect buttons to other functions self.location = 0 QtCore.QObject.connect(self.actionQuit, QtCore.SIGNAL("triggered()"), MainWindow.close) QtCore.QObject.connect(self.quitButton, QtCore.SIGNAL("released()"), MainWindow.close) QtCore.QObject.connect(self.settingsButton, QtCore.SIGNAL("released()"), self.setSettings) QtCore.QObject.connect(self.actionSettings, QtCore.SIGNAL("triggered()"), self.setSettings) QtCore.QObject.connect(self.loadButton, QtCore.SIGNAL("released()"), self.load_file_dialog) QtCore.QObject.connect(self.actionSave_Game, QtCore.SIGNAL("triggered()"),self.save_file_dialog) QtCore.QObject.connect(self.doneButton, QtCore.SIGNAL("released()"), self.goBack) QtCore.QObject.connect(self.startButton, QtCore.SIGNAL("released()"), self.newGame) QtCore.QObject.connect(self.actionMain_Menu, QtCore.SIGNAL("triggered()"), self.setMain) QtCore.QObject.connect(self.actionHelp, QtCore.SIGNAL("triggered()"), self.setInstructions) QtCore.QObject.connect(self.instrButton, QtCore.SIGNAL("released()"), self.setInstructions) QtCore.QObject.connect(self.doneButton2, QtCore.SIGNAL("released()"), self.goBack) QtCore.QObject.connect(self.doneButton3, QtCore.SIGNAL("released()"), self.goBack) QtCore.QObject.connect(self.actionCredits, QtCore.SIGNAL("triggered()"), self.setCredits) self.latLongCheck.stateChanged.connect(self.latLong) self.colorCheck.stateChanged.connect(self.colorize) self.legendCheck.stateChanged.connect(self.legend) QtCore.QObject.connect(self.searchButton, QtCore.SIGNAL("released()"), self.doSearch) QtCore.QObject.connect(self.nextButton, QtCore.SIGNAL("released()"), self.storyButton) self.volumeSlider.sliderMoved.connect(self.setVol) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): pass #Custom signals are here def setSettings(self): self.background.setPixmap(self.backgroundPixmapSettings) self.stackedWidget.setCurrentIndex(1) def setInstructions(self): self.background.setPixmap(self.backgroundPixmapSettings) self.stackedWidget.setCurrentIndex(3) def setCredits(self): self.background.setPixmap(self.backgroundPixmapSettings) self.stackedWidget.setCurrentIndex(4) def goBack(self): self.stackedWidget.setCurrentIndex(self.location) if self.location == 0: self.background.setPixmap(self.backgroundPixmapMenu) else: None #Should be something here later. def load_file_dialog(self): fd = QFileDialog() self.filename = fd.getOpenFileName(None, "Load Saved Game", "saves", "MapMaster Save files (*.save)") if isfile(self.filename): self.loadSaved = True self.stackedWidget.setCurrentIndex(2) self.location = 2 self.soundManager.switchSongs(self.location) def save_file_dialog(self): filename = QtGui.QFileDialog.getSaveFileName(None,"Save Game", "saves", "MapMaster Save files (*.save)") if filename == "": print "No file specified!" else: if ".save" in filename: self.fname = open(filename, "w") else: self.fname = open(filename + ".save",'w') score = str(self.data.score) numClues = str(len(self.data.clueStack)) charX, charY = self.data.character.getCenter() whiteSpace = " " toWriteList = whiteSpace + str(charX) + whiteSpace + str(charY) + whiteSpace + numClues + whiteSpace + score self.fname.write(toWriteList) self.fname.close() def newGame(self): self.background.setPixmap(self.backgroundPixmapSettings) self.filename = None self.stackedWidget.setCurrentIndex(5) self.location = 5 def storyButton(self): self.stackedWidget.setCurrentIndex(2) self.location = 2 self.soundManager.switchSongs(self.location) def setMain(self): self.save_file_dialog() self.background.setPixmap(self.backgroundPixmapMenu) self.stackedWidget.setCurrentIndex(0) self.location = 0 self.soundManager.switchSongs(self.location) def latLong(self): if self.latLongCheck.isChecked(): print "Lat/long overlay on" else: print "Lat/long overlay off" self.data.overlays['latLongOverlay'].mViewObj.setVisible(self.latLongCheck.isChecked()) def colorize(self): if self.colorCheck.isChecked(): print "Color overlay on" else: print "Color overlay off" self.data.overlays['colorOverlay'].mViewObj.setVisible(self.colorCheck.isChecked()) def legend(self): if self.legendCheck.isChecked(): print "Legend overlay on" else: print "Legend overlay off" self.data.overlays['legendOverlay'].mViewObj.setVisible(self.legendCheck.isChecked()) def setVol(self): self.soundManager.setVolume(self.volumeSlider.sliderPosition()) def doSearch(self): searchLandmark(self.data)
class TermPayDialog(QDialog): holdc = {} def __init__(self, student, term, parent=None): super(TermPayDialog, self).__init__(parent) #term data self.term = term terms = self.pullOnes('terms', self.term) session = self.pullOnes('session', terms['sessionID']) self.termname = str( session['name']) + ' ' + terms['name'] + ' Term Report' self.pagetitle = self.termname #student data self.student = student st = self.pullStudent(self.student) fullname = str(st['surname'] + ' ' + st['firstname'] + ' ' + st['othername']).title() schno = st['schno'] db_class = 'student_class' + str(self.term) student_clasz = self.pullOne(db_class, {'studentID': self.student}) clasz = self.pullOne('datas', {'id': student_clasz['classID']}) self.clasz = clasz['subID'] armz = self.pullOne('datas', {'id': clasz['subID']}) classname = armz['abbrv'] + ' ' + clasz['abbrv'] #pull all CA fullNameText = QLabel(fullname) schnoText = QLabel(schno) classText = QLabel(classname) topLay = QGridLayout() topLay.addWidget(fullNameText, 0, 0) topLay.addWidget(schnoText, 1, 0) topLay.addWidget(classText, 2, 0) groupBox = QGroupBox('Current Payment') groupBox.setLayout(topLay) payAmountText = QLabel('Amount') self.payBalanceText = QLabel('Balance') self.payBalanceAmount = QLabel('0.0') self.payAmount = QLineEdit() self.payAmount.setObjectName("pay") self.payAmount.setPlaceholderText("000.00") payText = QLabel('Select Account') self.payMethod = QComboBox() accounts = self.pullAccount() self.holdaccount = {} i = 0 for h in accounts: tex = str(h['name']).upper() self.payMethod.addItem(tex) self.holdaccount[i] = h['id'] payDateText = QLabel('Balance') self.payDate = QDateEdit() self.payDate.setDateTime(QDateTime.currentDateTime()) self.payDate.setCalendarPopup(True) tellerText = QLabel('Teller/Receipt No.') self.teller = QLineEdit() self.teller.setObjectName("teller") self.teller.textChanged.connect(self.pullTeller) self.teller.setPlaceholderText("0000000") self.hw = QGridLayout() self.hw.addWidget(payAmountText, 0, 0) self.hw.addWidget(self.payAmount, 0, 1) self.hw.addWidget(tellerText, 0, 2) self.hw.addWidget(self.teller, 0, 3) self.hw.addWidget(payText, 1, 0) self.hw.addWidget(self.payMethod, 1, 1) self.hw.addWidget(payDateText, 1, 2) self.hw.addWidget(self.payDate, 1, 3) head_col1 = QLabel('ITEM') head_col2 = QLabel('AMOUNT') head_col3 = QLabel('FULL PAY') head_col4 = QLabel('PART PAY') head_col5 = QLabel('BALANCE') layout1 = QGridLayout() layout1.addWidget(head_col1, 0, 0) layout1.addWidget(head_col2, 0, 1) layout1.addWidget(head_col3, 0, 2) layout1.addWidget(head_col4, 0, 3) layout1.addWidget(head_col5, 0, 4) arr = self.pullFees() feex = arr[1] payx = arr[2] normal_pay = [] full_pay = [] part_pay = [] bal_pay = [] ko = 1 self.holdval = [] self.holdfee = {} self.holdtextfee = {} self.holdtextfeeperm = {} self.holdpaid = {} self.holdcpaid = {} self.holdtextpaid = {} self.holdpayments = {} self.holdtextbal = {} self.holdbal = {} for val in arr[0]: paid = False s_normal_pay = [] s_full_pay = [] s_part_pay = [] self.holdval.append(val) mz = self.pullOne('datas', {'id': val}) self.num = val self.d = QLabel('Text') self.d.setText(str(mz['name']).upper()) self.d1 = QLabel() if val in feex: fk = feex[int(val)].values() normal_pay.append(float(fk[0])) s_normal_pay.append(float(fk[0])) self.d1.setText(str("{:,}".format(float(fk[0]))).upper()) else: self.d1.setText(str('-.-').upper()) nHbo1 = QVBoxLayout() if val in feex: fk = feex[int(val)].values() fky = feex[int(val)].keys() self.c = QCheckBox('cb' + str(val)) self.c.setEnabled(False) self.c.setText(str("{:,}".format(float(fk[0]))).upper()) self.c.setObjectName("chk" + str(val)) self.holdfee[int(val)] = self.c self.holdtextfee[int(val)] = fk[0] self.holdtextfeeperm[int(val)] = fk[0] self.c.toggled.connect(lambda state, x=fky[0], fee=int( val), money=fk[0]: self.chkFunc(x, fee, money, self.c)) if (val in payx) and len(payx[int(val)]) == 1: pk = payx[int(val)].values() self.c.setChecked(True) if float(pk[0]) == float(fk[0]): full_pay.append(float(fk[0])) s_full_pay.append(float(fk[0])) paid = True else: self.c.setChecked(False) nHbo1.addWidget(self.c) else: nHbo1.addWidget(QLabel('-.-')) #nHbo1.hide() nHbo2 = QHBoxLayout() fk = feex[int(val)].values() fky = feex[int(val)].keys() c2 = QCheckBox() c2.setEnabled(False) c2.setMaximumWidth(15) c2.setObjectName("chk2" + str(val)) p = QLineEdit() p.setDisabled(True) p.setMaximumWidth(50) p.setFixedWidth(51) p.setObjectName("pay" + str(val)) p.setPlaceholderText("00.0") self.holdpaid[int(val)] = p self.holdcpaid[int(val)] = c2 self.holdtextpaid[int(val)] = list() c2.toggled.connect( lambda state, x=fky[0], fee=int(val): self.chkFunc1(x, fee, p)) if paid == False: nHbo2.addWidget(c2) nHbo2.addWidget(p) if val in payx and len(payx[val]) > 0: for j in payx[int(val)]: self.c1 = QCheckBox('cb1' + str(j)) self.c1.setEnabled(False) self.c1.setText(str(payx[int(val)][j]).upper()) self.c1.setObjectName("chk" + str(j)) self.c1.toggled.connect( lambda state, x=j: self.chkFunc1(x)) self.c1.setChecked(True) part_pay.append(float(fk[0])) s_part_pay.append(float(fk[0])) self.holdpayments[j] = self.c1 self.holdtextpaid[val].append(float(fk[0])) nHbo2.addWidget(self.c1) else: pass else: p.hide() c2.hide() nHbo2.addWidget(c2) nHbo2.addWidget(p) s_tot = sum(s_normal_pay) - (sum(s_full_pay) + sum(s_part_pay)) bal_pay.append(float(s_tot)) d2 = QLabel('') self.holdbal[int(val)] = d2 d2.setText(str("{:,}".format(s_tot)).upper()) self.holdtextbal[int(val)] = s_tot layout1.addWidget(self.d, ko, 0) layout1.addWidget(self.d1, ko, 1) layout1.addLayout(nHbo1, ko, 2) layout1.addLayout(nHbo2, ko, 3) layout1.addWidget(d2, ko, 4) ko += 1 normal_payx = sum(normal_pay) full_payx = sum(full_pay) part_payx = sum(part_pay) bal_payx = sum(bal_pay) self.head_col1 = QLabel('ITEM') self.head_col2 = QLabel(str("{:,}".format(normal_payx)).upper()) self.head_col3 = QLabel(str("{:,}".format(full_payx)).upper()) self.head_col4 = QLabel(str("{:,}".format(part_payx)).upper()) self.head_col5 = QLabel(str("{:,}".format(bal_payx)).upper()) layout1.addWidget(self.head_col1, ko, 0) layout1.addWidget(self.head_col2, ko, 1) layout1.addWidget(self.head_col3, ko, 2) layout1.addWidget(self.head_col4, ko, 3) layout1.addWidget(self.head_col5, ko, 4) self.hw1 = QGridLayout() self.hw1.addWidget(self.payBalanceText, 0, 0) self.hw1.addWidget(self.payBalanceAmount, 1, 0) second1 = QGridLayout() second1.addLayout(self.hw, 0, 0) second1.addLayout(layout1, 1, 0) second1.addLayout(self.hw1, 2, 0) groupBox1 = QGroupBox('Current Payment') groupBox1.setLayout(second1) self.pb = QPushButton() self.pb.setObjectName("Add") self.pb.setText("Add Fees") self.pb1 = QPushButton() self.pb1.setObjectName("Cancel") self.pb1.setText("Cancel") self.pb2 = QPushButton() self.pb2.setObjectName("Add") self.pb2.setText("Print Receipts") hbo = QHBoxLayout() hbo.addWidget(self.pb1) hbo.addStretch() hbo.addWidget(self.pb) hbo.addStretch() hbo.addWidget(self.pb2) groupBox2 = QGroupBox('') groupBox2.setLayout(hbo) grid = QGridLayout() grid.addWidget(groupBox, 0, 0) grid.addWidget(groupBox1, 1, 0) grid.addWidget(groupBox2, 2, 0) self.setLayout(grid) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_close(self)) self.setWindowTitle(self.pagetitle) def reCalFull(self): fees_arr = self.holdfee fee_store = list() for a in fees_arr: if fees_arr[a].isChecked() == True: h = self.holdtextfee[a] fee_store.append(float(h)) else: pass fee_sum = sum(fee_store) self.head_col3.setText('{:,}'.format(fee_sum)) def reCalPart(self): fees_arr = self.holdtextpaid fee_store = list() for a in fees_arr: if self.holdtextpaid[a]: h = sum(self.holdtextpaid[a]) fee_store.append(float(h)) fee_sum = sum(fee_store) self.head_col4.setText('{:,}'.format(fee_sum)) def reCalBal(self): bal_arr = self.holdbal bal_store = list() for a in bal_arr: h = self.holdtextbal[a] bal_store.append(float(h)) bal_sum = sum(bal_store) self.head_col5.setText('{:,}'.format(bal_sum)) def reCalSingleBal(self): bal_arr = self.holdval fees_arr = self.holdfee for a in bal_arr: if fees_arr[a].isChecked() == True: b = self.holdtextfee[a] self.holdbal[a].setText('{:,}'.format(0)) self.holdtextbal[a] = 0 elif fees_arr[a].isChecked() == False: b = self.holdtextfee[a] self.holdbal[a].setText('{:,}'.format(float(b))) self.holdtextbal[a] = float(b) self.reCalBal() def chkFunc(self, a, c, d, b): # checkbox select to make fuul payment self.a = a db_fee = 'student_fee' + str(self.term) db_pay = 'student_pay' + str(self.term) amount = self.payAmount.text() teller = self.teller.text() # get all paments made for that fee # get the check box g = Db() fee = g.selectn(db_fee, '', 1, {'id': a}) loc = self.holdfee[int(fee['feeID'])] poc = self.holdpaid[int(fee['feeID'])] pocc = self.holdcpaid[int(fee['feeID'])] try: ## fee was checked full pay ## confirm if money posted and its greater than or equals # confimr if teller number was provided ## if those conditions are met payment of fees is possible if (float(amount) >= float(d)) and len(str(teller)) > 0: # confirm if the checkbox was checked if loc.isChecked() == True: #if it was checked prepare to insert payment data pay = {} pay['studentID'] = self.student pay['accountID'] = self.payAmount.text() pay['amount'] = d pay['teller'] = teller pay['feeID'] = fee['feeID'] pay['datepaid'] = self.payDate.date().toPyDate() # however confirm if full payment had bee made b4 dat = g.select(db_pay, '', '', { 'studentID': self.student, 'feeID': fee['feeID'] }) if dat and len(dat) > 0 and float( dat[0]['amount']) > 0 and float( dat[0]['amount']) == float(d): # full payment made # dont post # keep part pay disabled poc.hide() pocc.hide() # inform user msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle("Info") msg.setText( "This fee has already been paid for. You cannot repay for it" ) msg.setStandardButtons(QMessageBox.Cancel) msg.exec_() else: # post payment h = g.insert(db_pay, pay) if int(h) > 0: # deduct from balance # keep part pay disabled] poc.hide() pocc.hide() # recalculate self.reCalFull() self.reCalSingleBal() else: poc.show() else: # money was not posted if len(str(self.teller.text())) > 0: pay = {} pay['studentID'] = self.student pay['teller'] = self.teller.text() pay['feeID'] = fee['feeID'] h = g.delete(db_pay, pay) poc.show() pocc.show() self.reCalFull() self.reCalSingleBal() else: msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle("Info") msg.setText( "Please provide the teller/receipt details before removing amount." ) msg.setStandardButtons(QMessageBox.Cancel) msg.exec_() #add to money ## if those conditions are not met # payment of fees is not possible # however user might want to revoke a payment # meaning checkbox was unchecked else: if loc.isChecked() == False: # prepare to remove payment pay = {} pay['studentID'] = self.student pay['teller'] = self.teller.text() pay['feeID'] = fee['feeID'] # remove payment h = g.delete(db_pay, pay) # confirm if removal was succesful if h == 1: # if successful poc.show() pocc.show() # refund balance # recalculate self.reCalFull() self.reCalSingleBal() else: # not sussefull # details not complete #restore it to check #loc.setChecked(True) poc.hide() pocc.hide() # inform user msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle("Safety Measure:") msg.setText( "You will need to enter the correct teller/receipt details for this payment before removing it" ) msg.setStandardButtons(QMessageBox.Cancel) msg.exec_() # user trying to make payment with no funds else: # uncheck user loc.setChecked(False) poc.show() pocc.show() #give info msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle(" Payment Error") msg.setText( "Please provide teller/receipt details or Insufficient funds to make full payments " ) msg.setStandardButtons(QMessageBox.Cancel) msg.exec_() except: if loc.isChecked() == False: # money was not posted if len(str(self.teller.text())) > 0: pay = {} pay['studentID'] = self.student pay['teller'] = self.teller.text() pay['feeID'] = fee['feeID'] h = g.delete(db_pay, pay) poc.show() pocc.show() self.reCalFull() self.reCalSingleBal() else: pass else: loc.setChecked(False) poc.show() pocc.show() msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle(" Payment Error:") msg.setText("Please insert amount and Teller/Receipt details ") msg.setStandardButtons(QMessageBox.Cancel) msg.exec_() def chkFunc1(self, a, b, c): # checkbox select to make fuul payment self.a = a db_fee = 'student_fee' + str(self.term) db_pay = 'student_pay' + str(self.term) amount = self.payAmount.text() teller = self.teller.text() # get all paments made for that fee # get the check box g = Db() fee = g.selectn(db_fee, '', 1, {'id': a}) loc = self.holdfee[b] payfull = self.holdtextfee[b] pocc = self.holdpaid[b] poc = self.holdcpaid[b] d = pocc.text() try: ## fee was checked full pay ## confirm if money posted and its greater than or equals # confimr if teller number was provided ## if those conditions are met payment of fees is possible if (float(amount) >= float(d)) and len(str(teller)) > 0: # confirm if the checkbox was checked if poc.isChecked() == True: #if it was checked prepare to insert payment data pay = {} pay['studentID'] = self.student pay['accountID'] = self.payAmount.text() pay['teller'] = teller pay['feeID'] = fee['feeID'] pay['datepaid'] = self.payDate.date().toPyDate() # however confirm if full payment had bee made b4 dat = g.selectn(db_pay, '', '', { 'studentID': self.student, 'feeID': fee['feeID'] }) if dat and len(dat) > 0: mon = list() for dd in dat: mon.append(float(dd['amount'])) # full payment made # dont post # keep part pay disabled total_money_paid = sum(mon) #no payments required if float(total_money_paid) >= float(payfull): pass #payment required elif float(total_money_paid) < float(payfull): if float(amount) >= float(d): pay['amount'] = d #post h = g.insert(db_pay, pay) if int(h) > 0: # deduct from balance # keep part pay disabled] loc.hide() pocc.setDisabled(True) # recalculate self.reCalFull() self.reCalPart() self.reCalSingleBal() else: poc.show() else: msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle("Info") msg.setText("Insufficient funds.") msg.setStandardButtons(QMessageBox.Cancel) msg.exec_() loc.hide() pocc.setDisabled(True) # inform user else: # post payment if float(amount) >= float(d): pay['amount'] = d #post h = g.insert(db_pay, pay) if int(h) > 0: # deduct from balance # keep part pay disabled] loc.hide() pocc.setDisabled(True) # recalculate self.reCalFull() self.reCalSingleBal() else: poc.show() # money was not posted if len(str(self.teller.text())) > 0: pay = {} pay['studentID'] = self.student pay['teller'] = self.teller.text() pay['feeID'] = fee['feeID'] h = g.delete(db_pay, pay) poc.show() pocc.show() self.reCalFull() self.reCalSingleBal() else: msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle("Info") msg.setText( "Please provide the teller/receipt details before removing amount." ) msg.setStandardButtons(QMessageBox.Cancel) msg.exec_() #add to money ## if those conditions are not met # payment of fees is not possible # however user might want to revoke a payment # meaning checkbox was unchecked else: if loc.isChecked() == False: # prepare to remove payment pay = {} pay['studentID'] = self.student pay['teller'] = self.teller.text() pay['feeID'] = fee['feeID'] # remove payment h = g.delete(db_pay, pay) # confirm if removal was succesful if h == 1: # if successful poc.show() pocc.show() # refund balance # recalculate self.reCalFull() self.reCalSingleBal() else: # not sussefull # details not complete #restore it to check #loc.setChecked(True) poc.hide() pocc.hide() # inform user msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle("Safety Measure:") msg.setText( "You will need to enter the correct teller/receipt details for this payment before removing it" ) msg.setStandardButtons(QMessageBox.Cancel) msg.exec_() # user trying to make payment with no funds else: # uncheck user loc.setChecked(False) poc.show() pocc.show() #give info msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle(" Payment Error") msg.setText( "Please provide teller/receipt details or Insufficient funds to make full payments " ) msg.setStandardButtons(QMessageBox.Cancel) msg.exec_() except: if loc.isChecked() == False: # money was not posted if len(str(self.teller.text())) > 0: pay = {} pay['studentID'] = self.student pay['teller'] = self.teller.text() pay['feeID'] = fee['feeID'] h = g.delete(db_pay, pay) poc.show() pocc.show() self.reCalFull() self.reCalSingleBal() else: pass else: loc.setChecked(False) poc.show() pocc.show() msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle(" Payment Error:") msg.setText("Please insert amount and Teller/Receipt details ") msg.setStandardButtons(QMessageBox.Cancel) msg.exec_() def getClass(self, x): # shost is a QString object class_arr = [] for i in self.cla_arr: if self.cla_arr[i].checkState(0) == Qt.Checked: class_arr.append(i) c = self.getClassStudent(class_arr) self.feesPop.setText('Total: ' + str(c[0])) self.cla = class_arr self.students = c[1] def pullStudent(self, student): cn = Db() arr = cn.selectn('students', '', 1, {'id': student}) return arr def pullTeller(self): cn = Con() teller = self.teller.text() if len(str(teller)) > 0: h1 = self.holdfee for x in h1: h1[x].setEnabled(True) h2 = self.holdpaid h3 = self.holdcpaid for x in h2: h2[x].setEnabled(True) h3[x].setEnabled(True) else: h1 = self.holdfee for x in h1: h1[x].setEnabled(False) h2 = self.holdpaid h3 = self.holdcpaid for x in h2: h2[x].setEnabled(False) h3[x].setEnabled(False) arr = cn.getTeller(self.term, self.student, teller) arr1 = cn.getNonTeller(self.term, self.student, teller) amount = self.payAmount.text() if amount and (float(amount) > 0): if arr1 and float(arr1['amount']) > 0: self.payBalanceAmount.setText('This teller :' + str(teller) + ' is already in use ') else: if arr and float(arr['amount']) > 0: amt = arr['amount'] amt_a = "{:,}".format(float(amt)) bl = float(amount) - float(amt) bl_a = "{:,}".format(float(bl)) self.payBalanceAmount.setText( 'The sum of' + str(amt_a) + ' has been deducted from this teller') self.payBalanceText.setText('Balance on ' + str(teller) + ' : ' + str(bl_a) + '') else: bl = float(amount) bl_a = "{:,}".format(float(bl)) self.payBalanceAmount.setText( 'No transaction on teller :' + str(teller)) self.payBalanceText.setText('Balance on ' + str(teller) + ' : ' + str(bl_a) + '') else: msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setWindowTitle("Error") msg.setText("Error! Please enter an amount before you proceed...") msg.setStandardButtons(QMessageBox.Cancel) msg.exec_() def pullFees(self): term = self.term student = self.student fee_id_array = [] cn = Db() db_fee = 'student_fee' + str(term) db_pay = 'student_pay' + str(term) fee = cn.selectn(db_fee, '', '', {'studentID': student}) pay = cn.selectn(db_pay, '', '', {'studentID': student}) #get all fees arr = {} arr1 = {} for r in fee: fee_id_array.append(int(r['feeID'])) arr[int(r['feeID'])] = {} for r in pay: fee_id_array.append(int(r['feeID'])) arr1[int(r['feeID'])] = {} for r in fee: get_mon = cn.selectn( 'datas', '', 1, { 'pubID': 'fee', 'subID': self.term, 'name': self.clasz, 'abbrv': r['feeID'] }) if arr[int(r['feeID'])] and isinstance(arr[int(r['feeID'])], dict): arr[int(r['feeID'])][int(r['id'])] = get_mon['description'] else: arr[int(r['feeID'])] = {} arr[int(r['feeID'])][int(r['id'])] = get_mon['description'] for r in pay: if arr1[int(r['feeID'])] and isinstance(arr1[int(r['feeID'])], dict): arr1[int(r['feeID'])][int(r['id'])] = r['amount'] else: arr1[int(r['feeID'])] = {} arr1[int(r['feeID'])][int(r['id'])] = r['amount'] fee_ids = list(set(fee_id_array)) fin = [fee_ids, arr, arr1] return fin def pullOne(self, a, b): cn = Db() arr = cn.selectn(a, '', 1, b) return arr def pullOnes(self, a, b): cn = Db() arr = cn.selectn(a, '', 1, {'id': b}) return arr def pullAccount(self): cn = Db() arr = cn.selectn('datas', '', '', {"pubID": 20, "active": 0}) return arr def pullRep(self): cn = Db() ca = "rep" arr = cn.selectn('datas', '', '', {"subID": self.sid, "pubID": ca}) return arr def button_close(self, b): b.close() def button_click(self): tex = ' Please wait processing, do not cancel or close..' self.feesPop.setText(tex) _term = self.term _class = self.cla _students = self.students _amount = self.feesAmount.text() _fee = self.hol[self.feesCombo.currentIndex()] for j in _class: data = {} data['pubID'] = 'fee' data['subID'] = _term data['abbrv'] = _fee data['name'] = j cn = Db() feeStudent = self.feeStudents(_term, _students, _fee, _amount) check = cn.selectn('datas', '', 1, data) if (check and check['id'] == 0): pass else: data['description'] = _amount cn.insert('datas', data) ins = feeStudent tex = ' TOTAL of ' + str(ins) + ' inserted' self.feesPop.setText(tex) def feeStudents(self, session, students, fee, amount): db = 'student_fee' + str(session) cn = Db() fd = [] ed = [] for s in students: data = {} data['studentID'] = s[0] data['feeID'] = fee chk = cn.selectn(db, '', 1, data) if (chk and int(chk['id']) > 0): #confirm if money available pass else: #if money not set , set e = cn.insert(db, data) ed.append(e) return len(ed) def lunchEditForm(self, row): term = self.term self.close() self.post = EditReportDialog(term, row) self.post.show() def lunchDeleteForm(self, row): cn = Db() arr = cn.update('datas', {"active": 1}) self.close() self.__init__(self.term, self.termname)
def initGui(): def setData(): buttonPath.setText(self.data["path"]) radioVisual.setChecked(self.data["isVisual"]) radioAnalytic.setChecked(not self.data["isVisual"]) chkBoxSquare.setChecked(self.data["isSquare"]) d1 = self.data["date1"] d2 = self.data["date2"] date1.setDate(d1) date2.setDate(d2) date1.setMaximumDate(d2.addDays(-1)) date2.setMinimumDate(d1.addDays(+1)) spinDay.setValue(d1.daysTo(d2)) def connect(): buttonOK.clicked.connect(self.onOK) buttonPath.clicked.connect(self.onPath) date1.dateChanged.connect(self.onDateChanged1) date2.dateChanged.connect(self.onDateChanged2) spinDay.valueChanged.connect(self.onValueChanged) windowTitle = "Setting download images Planet Labs" self.setWindowTitle(windowTitle) self.setWindowIcon(icon) grpImage = QGroupBox("Images", self) radioVisual = QRadioButton("Visual", grpImage) radioVisual.setObjectName("rbVisual") radioAnalytic = QRadioButton("Analytic", grpImage) chkBoxSquare = QCheckBox("Square thumbnail", grpImage) chkBoxSquare.setObjectName("cbBoxSquare") buttonPath = QPushButton(self.titleSelectDirectory, grpImage) buttonPath.setObjectName("pbPath") layoutRadioButtons = QHBoxLayout() for item in (radioVisual, radioAnalytic): layoutRadioButtons.addWidget(item) layoutImage = QVBoxLayout(grpImage) layoutImage.addLayout(layoutRadioButtons) layoutImage.addWidget(chkBoxSquare) layoutImage.addWidget(buttonPath) grpDateSearch = QGroupBox("Dates for search", self) date1 = QDateEdit(grpDateSearch) date1.setObjectName("deDate1") date2 = QDateEdit(grpDateSearch) date2.setObjectName("deDate2") for item in [date1, date2]: item.setCalendarPopup(True) format = item.displayFormat().replace("yy", "yyyy") item.setDisplayFormat(format) spinDay = QSpinBox(grpDateSearch) spinDay.setObjectName("sbDay") spinDay.setSingleStep(1) spinDay.setSuffix(" Days") spinDay.setRange(1, 1000 * 360) layoutDate = QHBoxLayout(grpDateSearch) layoutDate.addWidget(QLabel("From", grpDateSearch)) layoutDate.addWidget(date1) layoutDate.addWidget(QLabel("To", grpDateSearch)) layoutDate.addWidget(date2) layoutDate.addWidget(spinDay) buttonOK = QPushButton("OK", self) layout = QVBoxLayout(self) layout.addWidget(grpImage) layout.addWidget(grpDateSearch) layout.addWidget(buttonOK) self.resize(5 * len(windowTitle) + 200, 30) if not self.data is None: setData() else: radioVisual.setChecked(True) radioAnalytic.setChecked(False) chkBoxSquare.setChecked(False) d2 = QDate.currentDate() d1 = d2.addMonths(-1) date1.setDate(d1) date2.setDate(d2) date1.setMaximumDate(d2.addDays(-1)) date2.setMinimumDate(d1.addDays(+1)) spinDay.setValue(d1.daysTo(d2)) connect()
class UnitForm(QDialog): def __init__(self, sid, parent=None): super(UnitForm, self).__init__(parent) self.sid = sid self.l1 = QLabel("Name") self.le = QLineEdit() self.le.setObjectName("host") self.le.setText("") self.l2 = QLabel("Abbrv.") self.le2 = QLineEdit() self.le2.setObjectName("Abbrv.") self.le2.setText("") self.pb = QPushButton() self.pb.setObjectName("Submit") self.pb.setText("Submit") self.pb1 = QPushButton() self.pb1.setObjectName("Cancel") self.pb1.setText("Cancel") layout = QFormLayout() layout.addRow(self.l1, self.le) layout.addRow(self.l2, self.le2) layout.addRow(self.pb1, self.pb) ko = 0 layout1 = QGridLayout() details = self.pullDetails(self.sid) detailsname = str(details[2]) arr = self.pullClass(self.sid) for i in arr: self.c = QCheckBox() self.c.setText(arr[i]) self.c.setObjectName("chk" + str(i)) self.b = QPushButton() self.b.setObjectName("btn" + str(i)) self.b.setText('Add') self.b1 = QPushButton() self.b1.setObjectName("btn1" + str(i)) self.b1.setText('Edit') self.connect(self.b, SIGNAL("clicked()"), lambda x=i: self.button_click(x)) self.connect(self.b1, SIGNAL("clicked()"), lambda y=i: self.button_click(y)) layout1.addWidget(self.c, ko, 0) layout1.addWidget(self.b, ko, 1) layout1.addWidget(self.b1, ko, 2) ko += 1 groupBox = QGroupBox('Add Class') groupBox.setLayout(layout) groupBox1 = QGroupBox('All Classes') groupBox1.setLayout(layout1) grid = QGridLayout() grid.addWidget(groupBox, 0, 0) grid.addWidget(groupBox1, 1, 0) self.setLayout(grid) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click(self.sid)) self.connect(self.pb1, SIGNAL("clicked()"), self.close) self.setWindowTitle(detailsname) def button_click(self, a): # shost is a QString object s1 = self.le.text() s2 = self.le2.text() self.a = a g = Db() if (len(s1) > 0): y = {'name': s1, 'subID': self.a, 'abbrv': s2} g.insert('datas', y) self.repaint() def button_click1(self, a): # shost is a QString object s1 = self.le.text() s2 = self.le2.text() self.a = a g = Db() if (len(s1) > 0): y = {'name': s1, 'subID': self.a, 'abbrv': s2} return g.insert('datas', y) def pullClass(self, a): self.a = a cn = Db() students = cn.select('datas', '', '', {'subID': self.a}) arr = {} for j in students: arr[j[0]] = j[2] return arr def pullDetails(self, a): self.a = a cn = Db() return cn.select('datas', '', 1, {'id': self.a})
def __init__(self, student, term, parent=None): super(TermPayDialog, self).__init__(parent) #term data self.term = term terms = self.pullOnes('terms', self.term) session = self.pullOnes('session', terms['sessionID']) self.termname = str( session['name']) + ' ' + terms['name'] + ' Term Report' self.pagetitle = self.termname #student data self.student = student st = self.pullStudent(self.student) fullname = str(st['surname'] + ' ' + st['firstname'] + ' ' + st['othername']).title() schno = st['schno'] db_class = 'student_class' + str(self.term) student_clasz = self.pullOne(db_class, {'studentID': self.student}) clasz = self.pullOne('datas', {'id': student_clasz['classID']}) self.clasz = clasz['subID'] armz = self.pullOne('datas', {'id': clasz['subID']}) classname = armz['abbrv'] + ' ' + clasz['abbrv'] #pull all CA fullNameText = QLabel(fullname) schnoText = QLabel(schno) classText = QLabel(classname) topLay = QGridLayout() topLay.addWidget(fullNameText, 0, 0) topLay.addWidget(schnoText, 1, 0) topLay.addWidget(classText, 2, 0) groupBox = QGroupBox('Current Payment') groupBox.setLayout(topLay) payAmountText = QLabel('Amount') self.payBalanceText = QLabel('Balance') self.payBalanceAmount = QLabel('0.0') self.payAmount = QLineEdit() self.payAmount.setObjectName("pay") self.payAmount.setPlaceholderText("000.00") payText = QLabel('Select Account') self.payMethod = QComboBox() accounts = self.pullAccount() self.holdaccount = {} i = 0 for h in accounts: tex = str(h['name']).upper() self.payMethod.addItem(tex) self.holdaccount[i] = h['id'] payDateText = QLabel('Balance') self.payDate = QDateEdit() self.payDate.setDateTime(QDateTime.currentDateTime()) self.payDate.setCalendarPopup(True) tellerText = QLabel('Teller/Receipt No.') self.teller = QLineEdit() self.teller.setObjectName("teller") self.teller.textChanged.connect(self.pullTeller) self.teller.setPlaceholderText("0000000") self.hw = QGridLayout() self.hw.addWidget(payAmountText, 0, 0) self.hw.addWidget(self.payAmount, 0, 1) self.hw.addWidget(tellerText, 0, 2) self.hw.addWidget(self.teller, 0, 3) self.hw.addWidget(payText, 1, 0) self.hw.addWidget(self.payMethod, 1, 1) self.hw.addWidget(payDateText, 1, 2) self.hw.addWidget(self.payDate, 1, 3) head_col1 = QLabel('ITEM') head_col2 = QLabel('AMOUNT') head_col3 = QLabel('FULL PAY') head_col4 = QLabel('PART PAY') head_col5 = QLabel('BALANCE') layout1 = QGridLayout() layout1.addWidget(head_col1, 0, 0) layout1.addWidget(head_col2, 0, 1) layout1.addWidget(head_col3, 0, 2) layout1.addWidget(head_col4, 0, 3) layout1.addWidget(head_col5, 0, 4) arr = self.pullFees() feex = arr[1] payx = arr[2] normal_pay = [] full_pay = [] part_pay = [] bal_pay = [] ko = 1 self.holdval = [] self.holdfee = {} self.holdtextfee = {} self.holdtextfeeperm = {} self.holdpaid = {} self.holdcpaid = {} self.holdtextpaid = {} self.holdpayments = {} self.holdtextbal = {} self.holdbal = {} for val in arr[0]: paid = False s_normal_pay = [] s_full_pay = [] s_part_pay = [] self.holdval.append(val) mz = self.pullOne('datas', {'id': val}) self.num = val self.d = QLabel('Text') self.d.setText(str(mz['name']).upper()) self.d1 = QLabel() if val in feex: fk = feex[int(val)].values() normal_pay.append(float(fk[0])) s_normal_pay.append(float(fk[0])) self.d1.setText(str("{:,}".format(float(fk[0]))).upper()) else: self.d1.setText(str('-.-').upper()) nHbo1 = QVBoxLayout() if val in feex: fk = feex[int(val)].values() fky = feex[int(val)].keys() self.c = QCheckBox('cb' + str(val)) self.c.setEnabled(False) self.c.setText(str("{:,}".format(float(fk[0]))).upper()) self.c.setObjectName("chk" + str(val)) self.holdfee[int(val)] = self.c self.holdtextfee[int(val)] = fk[0] self.holdtextfeeperm[int(val)] = fk[0] self.c.toggled.connect(lambda state, x=fky[0], fee=int( val), money=fk[0]: self.chkFunc(x, fee, money, self.c)) if (val in payx) and len(payx[int(val)]) == 1: pk = payx[int(val)].values() self.c.setChecked(True) if float(pk[0]) == float(fk[0]): full_pay.append(float(fk[0])) s_full_pay.append(float(fk[0])) paid = True else: self.c.setChecked(False) nHbo1.addWidget(self.c) else: nHbo1.addWidget(QLabel('-.-')) #nHbo1.hide() nHbo2 = QHBoxLayout() fk = feex[int(val)].values() fky = feex[int(val)].keys() c2 = QCheckBox() c2.setEnabled(False) c2.setMaximumWidth(15) c2.setObjectName("chk2" + str(val)) p = QLineEdit() p.setDisabled(True) p.setMaximumWidth(50) p.setFixedWidth(51) p.setObjectName("pay" + str(val)) p.setPlaceholderText("00.0") self.holdpaid[int(val)] = p self.holdcpaid[int(val)] = c2 self.holdtextpaid[int(val)] = list() c2.toggled.connect( lambda state, x=fky[0], fee=int(val): self.chkFunc1(x, fee, p)) if paid == False: nHbo2.addWidget(c2) nHbo2.addWidget(p) if val in payx and len(payx[val]) > 0: for j in payx[int(val)]: self.c1 = QCheckBox('cb1' + str(j)) self.c1.setEnabled(False) self.c1.setText(str(payx[int(val)][j]).upper()) self.c1.setObjectName("chk" + str(j)) self.c1.toggled.connect( lambda state, x=j: self.chkFunc1(x)) self.c1.setChecked(True) part_pay.append(float(fk[0])) s_part_pay.append(float(fk[0])) self.holdpayments[j] = self.c1 self.holdtextpaid[val].append(float(fk[0])) nHbo2.addWidget(self.c1) else: pass else: p.hide() c2.hide() nHbo2.addWidget(c2) nHbo2.addWidget(p) s_tot = sum(s_normal_pay) - (sum(s_full_pay) + sum(s_part_pay)) bal_pay.append(float(s_tot)) d2 = QLabel('') self.holdbal[int(val)] = d2 d2.setText(str("{:,}".format(s_tot)).upper()) self.holdtextbal[int(val)] = s_tot layout1.addWidget(self.d, ko, 0) layout1.addWidget(self.d1, ko, 1) layout1.addLayout(nHbo1, ko, 2) layout1.addLayout(nHbo2, ko, 3) layout1.addWidget(d2, ko, 4) ko += 1 normal_payx = sum(normal_pay) full_payx = sum(full_pay) part_payx = sum(part_pay) bal_payx = sum(bal_pay) self.head_col1 = QLabel('ITEM') self.head_col2 = QLabel(str("{:,}".format(normal_payx)).upper()) self.head_col3 = QLabel(str("{:,}".format(full_payx)).upper()) self.head_col4 = QLabel(str("{:,}".format(part_payx)).upper()) self.head_col5 = QLabel(str("{:,}".format(bal_payx)).upper()) layout1.addWidget(self.head_col1, ko, 0) layout1.addWidget(self.head_col2, ko, 1) layout1.addWidget(self.head_col3, ko, 2) layout1.addWidget(self.head_col4, ko, 3) layout1.addWidget(self.head_col5, ko, 4) self.hw1 = QGridLayout() self.hw1.addWidget(self.payBalanceText, 0, 0) self.hw1.addWidget(self.payBalanceAmount, 1, 0) second1 = QGridLayout() second1.addLayout(self.hw, 0, 0) second1.addLayout(layout1, 1, 0) second1.addLayout(self.hw1, 2, 0) groupBox1 = QGroupBox('Current Payment') groupBox1.setLayout(second1) self.pb = QPushButton() self.pb.setObjectName("Add") self.pb.setText("Add Fees") self.pb1 = QPushButton() self.pb1.setObjectName("Cancel") self.pb1.setText("Cancel") self.pb2 = QPushButton() self.pb2.setObjectName("Add") self.pb2.setText("Print Receipts") hbo = QHBoxLayout() hbo.addWidget(self.pb1) hbo.addStretch() hbo.addWidget(self.pb) hbo.addStretch() hbo.addWidget(self.pb2) groupBox2 = QGroupBox('') groupBox2.setLayout(hbo) grid = QGridLayout() grid.addWidget(groupBox, 0, 0) grid.addWidget(groupBox1, 1, 0) grid.addWidget(groupBox2, 2, 0) self.setLayout(grid) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_close(self)) self.setWindowTitle(self.pagetitle)
class PlayConfigTab(QWidget): """Display Config tab""" def __init__(self, parent): super(PlayConfigTab, self).__init__(parent) self.setupUi() def setupUi(self): """layout the window""" self.setContentsMargins(0, 0, 0, 0) vlayout = QVBoxLayout(self) vlayout.setContentsMargins(0, 0, 0, 0) sliderLayout = QHBoxLayout() self.kcfg_showShadows = QCheckBox(m18n('Show tile shadows'), self) self.kcfg_showShadows.setObjectName('kcfg_showShadows') self.kcfg_rearrangeMelds = QCheckBox( m18n('Rearrange undisclosed tiles to melds'), self) self.kcfg_rearrangeMelds.setObjectName('kcfg_rearrangeMelds') self.kcfg_showOnlyPossibleActions = QCheckBox( m18n('Show only possible actions')) self.kcfg_showOnlyPossibleActions.setObjectName( 'kcfg_showOnlyPossibleActions') self.kcfg_propose = QCheckBox(m18n('Propose what to do')) self.kcfg_propose.setObjectName('kcfg_propose') self.kcfg_animationSpeed = QSlider(self) self.kcfg_animationSpeed.setObjectName('kcfg_animationSpeed') self.kcfg_animationSpeed.setOrientation(Qt.Horizontal) self.kcfg_animationSpeed.setSingleStep(1) lblSpeed = QLabel(m18n('Animation speed:')) lblSpeed.setBuddy(self.kcfg_animationSpeed) sliderLayout.addWidget(lblSpeed) sliderLayout.addWidget(self.kcfg_animationSpeed) self.kcfg_useSounds = QCheckBox(m18n('Use sounds if available'), self) self.kcfg_useSounds.setObjectName('kcfg_useSounds') self.kcfg_uploadVoice = QCheckBox(m18n('Let others hear my voice'), self) self.kcfg_uploadVoice.setObjectName('kcfg_uploadVoice') pol = QSizePolicy() pol.setHorizontalPolicy(QSizePolicy.Expanding) pol.setVerticalPolicy(QSizePolicy.Expanding) spacerItem = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Expanding) vlayout.addWidget(self.kcfg_showShadows) vlayout.addWidget(self.kcfg_rearrangeMelds) vlayout.addWidget(self.kcfg_showOnlyPossibleActions) vlayout.addWidget(self.kcfg_propose) vlayout.addWidget(self.kcfg_useSounds) vlayout.addWidget(self.kcfg_uploadVoice) vlayout.addLayout(sliderLayout) vlayout.addItem(spacerItem) self.setSizePolicy(pol) self.retranslateUi() def retranslateUi(self): """translate to current language""" pass
def populateStatusBar(): statusBar = self.statusBar() w = QCheckBox( "Render", self ) w.setObjectName( 'renderCheck') w.setToolTip( "Toggle map rendering" ) w.setChecked( True ) statusBar.addPermanentWidget( w ) w = QCheckBox( "Marker", self ) w.setObjectName( 'markerCheck') w.setToolTip( "Toggle marker with cursor position from main map" ) w.setChecked( False ) statusBar.addPermanentWidget( w, 1 ) w = QCheckBox( "Extent", self ) w.setObjectName( 'extentCheck') w.setToolTip( "Show extent of main map" ) w.setChecked( False ) statusBar.addPermanentWidget( w, 1 ) w = QToolButton(self) w.setObjectName( 'highlightBtn') w.setToolTip( "Highlight extent in main map" ) w.setText("Highlight") statusBar.addPermanentWidget( w, 1 ) w = QLabel( "Scale factor:", self ) w.setObjectName( 'scaleFactorLabel') w.setAlignment(Qt.AlignRight | Qt.AlignVCenter) statusBar.addPermanentWidget( w, 1 ) w = QDoubleSpinBox(self) w.setObjectName( 'scaleFactorSpin') w.setToolTip( "Current scale factor of main map" ) w.setMinimum(0.0) w.setMaximum(1000.0) w.setDecimals(3) w.setValue(1) w.setSingleStep(.05) statusBar.addPermanentWidget( w, 1 ) w = QToolButton(self) w.setObjectName( 'scaleBtn') w.setToolTip( "Set scale for main map" ) w.setText("Scale: ") statusBar.addPermanentWidget( w, 1 )
class Form(QDialog): def __init__(self, parent=None): super(Form, self).__init__(parent) ko = 0 layout1 = QGridLayout() arr = self.pullClass(1) hold = {} for val in arr: self.num = val self.c = QCheckBox('cb' + str(val)) self.c.setText(arr[val][0]) self.c.setObjectName("chk" + str(val)) if (arr[val][1] == 1): self.c.setChecked(False) else: self.c.setChecked(True) self.c.stateChanged.connect( lambda state, x=val, y=self.c: self.chkFunc(x, y)) self.b = QPushButton() self.b.setObjectName("btn" + str(val)) self.b.setText('Subunit') self.b1 = QPushButton() self.b1.setObjectName("btn1" + str(val)) self.b1.setText('Edit') hold["btn" + str(val)] = self.b hold["btnx" + str(val)] = self.b1 layout1.addWidget(self.c, ko, 0) layout1.addWidget(self.b, ko, 1) layout1.addWidget(self.b1, ko, 2) ko += 1 for j in arr: self.h = j b = "btn" + str(j) b1 = "btnx" + str(j) self.connect(hold[b], SIGNAL("clicked()"), lambda gh=j: self.lunchUnitForm(gh)) self.connect(hold[b1], SIGNAL("clicked()"), lambda gh=j: self.lunchEditForm(gh)) groupBox1 = QGroupBox('All Classes') groupBox1.setLayout(layout1) self.pb = QPushButton() self.pb.setObjectName("Add") self.pb.setText("Add Class") self.pb1 = QPushButton() self.pb1.setObjectName("Cancel") self.pb1.setText("Cancel") hbo = QHBoxLayout() hbo.addWidget(self.pb1) hbo.addStretch() hbo.addWidget(self.pb) groupBox2 = QGroupBox('') groupBox2.setLayout(hbo) grid = QGridLayout() grid.addWidget(groupBox1, 0, 0) grid.addWidget(groupBox2, 1, 0) self.setLayout(grid) adF = AddForm() self.connect(self.pb, SIGNAL("clicked()"), lambda: adF.show()) self.connect(self.pb1, SIGNAL("clicked()"), self.close) self.setWindowTitle("Class Manager") def button_click(self, a): # shost is a QString object s1 = self.le.text() s2 = self.le2.text() self.a = a g = Db() if (len(s1) > 0): y = {'name': s1, 'subID': self.a, 'abbrv': s2} return g.insert('datas', y) def button_click1(self, a): # shost is a QString object s1 = self.le.text() s2 = self.le2.text() self.a = a g = Db() if (len(s1) > 0): y = {'name': s1, 'subID': self.a, 'abbrv': s2} j = g.insert('datas', y) return j def chkFunc(self, a, b): # shost is a QString object self.a = a self.b = b if b.isChecked() == True: y = {'active': 0} else: y = {'active': 1} g = Db() z = {'id': self.a} j = g.update('datas', y, z) return j def pullClass(self, a): self.a = a cn = Db() students = cn.select('datas', '', '', {'subID': self.a}) arr = {} for j in students: arr[j[0]] = [j[2], j[4], j[0]] return arr def lunchUnitForm(self, a): self.a = a self.form = UnitForm(self.a) self.form.show() #form.exec_() def lunchEditForm(self, a): self.a = a self.form = EditForm(self.a) self.form.show()
class QgsAnnotationWidget(QWidget): def __init__(self, parent, item): QWidget.__init__(self, parent) self.gridLayout_2 = QGridLayout(self) self.gridLayout_2.setObjectName(("gridLayout_2")) self.mMapPositionFixedCheckBox = QCheckBox(self) self.mMapPositionFixedCheckBox.setObjectName( ("mMapPositionFixedCheckBox")) self.gridLayout_2.addWidget(self.mMapPositionFixedCheckBox, 0, 0, 1, 1) self.gridLayout = QGridLayout() self.gridLayout.setObjectName(("gridLayout")) self.mFrameColorButton = QgsColorButton(self) self.mFrameColorButton.setText(("")) self.mFrameColorButton.setObjectName(("mFrameColorButton")) self.gridLayout.addWidget(self.mFrameColorButton, 3, 1, 1, 1) self.mFrameColorButton.colorChanged.connect( self.on_mFrameColorButton_colorChanged) self.mBackgroundColorLabel = QLabel(self) self.mBackgroundColorLabel.setObjectName(("mBackgroundColorLabel")) self.gridLayout.addWidget(self.mBackgroundColorLabel, 2, 0, 1, 1) self.mMapMarkerLabel = QLabel(self) self.mMapMarkerLabel.setObjectName(("mMapMarkerLabel")) self.gridLayout.addWidget(self.mMapMarkerLabel, 0, 0, 1, 1) self.mBackgroundColorButton = QgsColorButton(self) self.mBackgroundColorButton.setText(("")) self.mBackgroundColorButton.setObjectName(("mBackgroundColorButton")) self.gridLayout.addWidget(self.mBackgroundColorButton, 2, 1, 1, 1) self.mBackgroundColorButton.colorChanged.connect( self.on_mBackgroundColorButton_colorChanged) self.mMapMarkerButton = QPushButton(self) self.mMapMarkerButton.setText(("")) self.mMapMarkerButton.setObjectName(("mMapMarkerButton")) self.gridLayout.addWidget(self.mMapMarkerButton, 0, 1, 1, 1) self.mMapMarkerButton.clicked.connect(self.on_mMapMarkerButton_clicked) self.mFrameWidthLabel = QLabel(self) self.mFrameWidthLabel.setObjectName(("mFrameWidthLabel")) self.gridLayout.addWidget(self.mFrameWidthLabel, 1, 0, 1, 1) self.mFrameWidthSpinBox = QDoubleSpinBox(self) self.mFrameWidthSpinBox.setObjectName(("mFrameWidthSpinBox")) self.gridLayout.addWidget(self.mFrameWidthSpinBox, 1, 1, 1, 1) self.mFrameColorLabel = QLabel(self) self.mFrameColorLabel.setObjectName(("mFrameColorLabel")) self.gridLayout.addWidget(self.mFrameColorLabel, 3, 0, 1, 1) self.gridLayout_2.addLayout(self.gridLayout, 1, 0, 1, 1) self.mMapMarkerLabel.setBuddy(self.mMapMarkerButton) self.mFrameWidthLabel.setBuddy(self.mFrameWidthSpinBox) self.setWindowTitle("QgsAnnotationWidgetBase") self.mMapPositionFixedCheckBox.setText("Fixed map position") self.mBackgroundColorLabel.setText("Background color") self.mMapMarkerLabel.setText("Map marker") self.mFrameWidthLabel.setText("Frame width") self.mFrameColorLabel.setText("Frame color") self.setLayout(self.gridLayout_2) self.mItem = item if (self.mItem != None): self.blockAllSignals(True) if (self.mItem.mapPositionFixed()): self.mMapPositionFixedCheckBox.setCheckState(Qt.Checked) else: self.mMapPositionFixedCheckBox.setCheckState(Qt.Unchecked) self.mFrameWidthSpinBox.setValue(self.mItem.frameBorderWidth()) self.mFrameColorButton.setColor(self.mItem.frameColor()) self.mFrameColorButton.setColorDialogTitle("Select frame color") self.mFrameColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel) self.mBackgroundColorButton.setColor( self.mItem.frameBackgroundColor()) self.mBackgroundColorButton.setColorDialogTitle( "Select background color") self.mBackgroundColorButton.setColorDialogOptions( QColorDialog.ShowAlphaChannel) self.symbol = self.mItem.markerSymbol() if (self.symbol != None): self.mMarkerSymbol = self.symbol.clone() self.updateCenterIcon() self.blockAllSignals(False) def apply(self): if (self.mItem != None): self.mItem.setMapPositionFixed( self.mMapPositionFixedCheckBox.checkState() == Qt.Checked) self.mItem.setFrameBorderWidth(self.mFrameWidthSpinBox.value()) self.mItem.setFrameColor(self.mFrameColorButton.color()) self.mItem.setFrameBackgroundColor( self.mBackgroundColorButton.color()) self.mItem.setMarkerSymbol(self.mMarkerSymbol) self.mMarkerSymbol = None #//item takes ownership self.mItem.update() def blockAllSignals(self, block): self.mMapPositionFixedCheckBox.blockSignals(block) self.mMapMarkerButton.blockSignals(block) self.mFrameWidthSpinBox.blockSignals(block) self.mFrameColorButton.blockSignals(block) def on_mMapMarkerButton_clicked(self): if (self.mMarkerSymbol == None): return markerSymbol = self.mMarkerSymbol.clone() dlg = QgsSymbolV2SelectorDialog(markerSymbol, QgsStyleV2.defaultStyle(), None, self) if (dlg.exec_() != QDialog.Rejected): self.mMarkerSymbol = markerSymbol self.updateCenterIcon() def on_mFrameColorButton_colorChanged(self, color): if (self.mItem == None): return self.mItem.setFrameColor(color) def updateCenterIcon(self): if (self.mMarkerSymbol == None): return icon = QgsSymbolLayerV2Utils.symbolPreviewIcon( self.mMarkerSymbol, self.mMapMarkerButton.iconSize()) self.mMapMarkerButton.setIcon(icon) def on_mBackgroundColorButton_colorChanged(self, color): if (self.mItem == None): return self.mItem.setFrameBackgroundColor(color)
def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.configOptions, self.checkBoxList, self.configBool = {}, {}, None # Check for root privileges if geteuid() != 0: msg = ("{} is not root. You need to run with root priviliges\n" "Please use kdesudo, gksu or sudo/sux.").format(getuser()) QMessageBox.critical(self, __doc__ + "- Error", msg) sys.exit(1) else: msg = "This tool is running with root priviliges." QMessageBox.warning(self, __doc__ + "- Warning", msg) # title, icon and sizes self.setWindowTitle(__doc__) self.setMinimumSize(600, 600) self.setMaximumSize(2048, 2048) self.resize(600, 600) self.setWindowIcon(QIcon.fromTheme("preferences-system")) self.menuBar().addMenu("&File").addAction("Exit", exit) QShortcut("Ctrl+q", self, activated=lambda: self.close()) # main group main_group = QGroupBox("Module configuration") self.setCentralWidget(main_group) self.layout = QVBoxLayout(main_group) # scrollarea widgets self.scrollArea, self.window = QScrollArea(), QWidget() self.layout.addWidget(self.scrollArea) self.vbox = QVBoxLayout(self.window) # Graphic effect glow = QGraphicsDropShadowEffect(self) glow.setOffset(0) glow.setBlurRadius(99) glow.setColor(QColor(99, 255, 255)) self.scrollArea.setGraphicsEffect(glow) glow.setEnabled(True) # config loading stuff self.findConfig(CONFIG_DIR) for eachOption in tuple(self.configOptions.keys()): self.readConfig(eachOption, self.configOptions) self.subLayout = QHBoxLayout() self.checkBoxName = "checkBox_" + eachOption checkBoxList = QCheckBox(self.checkBoxName, self) self.checkBoxList[self.checkBoxName] = checkBoxList checkBoxList.setObjectName(self.checkBoxName) checkBoxList.setText("Enable module {}".format(eachOption)) if self.tooltip is not '': checkBoxList.setToolTip(self.tooltip) else: tooltip = "Configuration settings for {}".format(eachOption) checkBoxList.setToolTip(tooltip) if self.configBool: checkBoxList.setChecked(True) self.subLayout.addWidget(checkBoxList) self.vbox.addLayout(self.subLayout) self.scrollArea.setWidget(self.window) # Bottom Buttons Bar self.pushButtonSleep = QPushButton("Sleep") self.pushButtonSleep.setToolTip("Trigger Suspend to RAM aka Sleep") self.pushButtonSleep.clicked.connect(self.sleep) self.pushButtonHibernate = QPushButton("Hibernate") self.pushButtonHibernate.setToolTip("Trigger Suspend to Disk Hibernate") self.pushButtonHibernate.clicked.connect(self.hibernate) self.buttonBox = QDialogButtonBox() self.buttonBox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Close | QDialogButtonBox.Help) self.buttonBox.addButton(self.pushButtonHibernate, QDialogButtonBox.ActionRole) self.buttonBox.addButton(self.pushButtonSleep, QDialogButtonBox.ActionRole) self.layout.addWidget(self.buttonBox) self.buttonBox.rejected.connect(exit) self.buttonBox.accepted.connect(self.writeConfig) self.buttonBox.helpRequested.connect(lambda: open_new_tab(WEBPAGE_URL))
class Dialog(QDialog): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self._document = None self._path = None mainLayout = QGridLayout() self.setLayout(mainLayout) tabs = QTabWidget() import_tab = QWidget() post_tab = QWidget() itabLayout = QGridLayout(import_tab) ptabLayout = QGridLayout(post_tab) tabs.addTab(import_tab, "musicxml2ly") tabs.addTab(post_tab, "after import") self.noartCheck = QCheckBox() self.norestCheck = QCheckBox() self.nolayoutCheck = QCheckBox() self.nobeamCheck = QCheckBox() self.useAbsCheck = QCheckBox() self.langCombo = QComboBox() self.langLabel = QLabel() self.impChecks = [ self.noartCheck, self.norestCheck, self.nolayoutCheck, self.nobeamCheck, self.useAbsCheck ] self.formatCheck = QCheckBox() self.trimDurCheck = QCheckBox() self.removeScalesCheck = QCheckBox() self.runEngraverCheck = QCheckBox() self.postChecks = [ self.formatCheck, self.trimDurCheck, self.removeScalesCheck, self.runEngraverCheck ] self.commandLineLabel = QLabel() self.commandLine = QTextEdit(acceptRichText=False) self.setChecksObjectNames() self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) userguide.addButton(self.buttons, "musicxml_import") self.langCombo.addItem('') self.langCombo.addItems(_langlist) itabLayout.addWidget(self.noartCheck, 0, 0, 1, 2) itabLayout.addWidget(self.norestCheck, 1, 0, 1, 2) itabLayout.addWidget(self.nolayoutCheck, 2, 0, 1, 2) itabLayout.addWidget(self.nobeamCheck, 3, 0, 1, 2) itabLayout.addWidget(self.useAbsCheck, 4, 0, 1, 2) itabLayout.addWidget(self.langLabel, 5, 0, 1, 2) itabLayout.addWidget(self.langCombo, 6, 0, 1, 2) itabLayout.addWidget(widgets.Separator(), 7, 0, 1, 2) itabLayout.addWidget(self.commandLineLabel, 8, 0, 1, 2) itabLayout.addWidget(self.commandLine, 9, 0, 1, 2) ptabLayout.addWidget(self.formatCheck, 0, 0, 1, 2) ptabLayout.addWidget(self.trimDurCheck, 1, 0, 1, 2) ptabLayout.addWidget(self.removeScalesCheck, 2, 0, 1, 2) ptabLayout.addWidget(self.runEngraverCheck, 3, 0, 1, 2) ptabLayout.setRowStretch(4, 10) mainLayout.addWidget(tabs, 0, 0, 9, 2) mainLayout.addWidget(self.buttons, 10, 0, 1, 2) app.translateUI(self) qutil.saveDialogSize(self, "xml_import/dialog/size", QSize(480, 260)) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) self.noartCheck.toggled.connect(self.makeCommandLine) self.norestCheck.toggled.connect(self.makeCommandLine) self.nolayoutCheck.toggled.connect(self.makeCommandLine) self.nobeamCheck.toggled.connect(self.makeCommandLine) self.useAbsCheck.toggled.connect(self.makeCommandLine) self.langCombo.currentIndexChanged.connect(self.makeCommandLine) self.makeCommandLine() self.loadSettings() def setChecksObjectNames(self): self.noartCheck.setObjectName("articulation-directions") self.norestCheck.setObjectName("rest-positions") self.nolayoutCheck.setObjectName("page-layout") self.nobeamCheck.setObjectName("import-beaming") self.useAbsCheck.setObjectName("absolute-mode") self.formatCheck.setObjectName("reformat") self.trimDurCheck.setObjectName("trim-durations") self.removeScalesCheck.setObjectName("remove-scaling") self.runEngraverCheck.setObjectName("engrave-directly") def translateUI(self): self.setWindowTitle(app.caption(_("Import Music XML"))) self.noartCheck.setText(_("Import articulation directions")) self.norestCheck.setText(_("Import rest positions")) self.nolayoutCheck.setText(_("Import page layout")) self.nobeamCheck.setText(_("Import beaming")) self.useAbsCheck.setText(_("Pitches in absolute mode")) self.commandLineLabel.setText(_("Command line:")) self.langLabel.setText(_("Language for pitch names")) self.langCombo.setItemText(0, _("Default")) self.formatCheck.setText(_("Reformat source")) self.trimDurCheck.setText(_("Trim durations (Make implicit per line)")) self.removeScalesCheck.setText(_("Remove fraction duration scaling")) self.runEngraverCheck.setText(_("Engrave directly")) self.buttons.button(QDialogButtonBox.Ok).setText(_("Run musicxml2ly")) def setDocument(self, path): """Set the full path to the MusicXML document.""" self._document = path def makeCommandLine(self): """Reads the widgets and builds a command line.""" cmd = ["$musicxml2ly"] if self.useAbsCheck.isChecked(): cmd.append('-a') if not self.noartCheck.isChecked(): cmd.append('--nd') if not self.norestCheck.isChecked(): cmd.append('--nrp') if not self.nolayoutCheck.isChecked(): cmd.append('--npl') if not self.nobeamCheck.isChecked(): cmd.append('--no-beaming') index = self.langCombo.currentIndex() if index > 0: cmd.append('--language=' + _langlist[index - 1]) cmd.append("$filename") self.commandLine.setText(' '.join(cmd)) def getCmd(self): """Returns the command line.""" cmd = [] for t in self.commandLine.toPlainText().split(): if t == '$musicxml2ly': cmd.extend(lilypondinfo.preferred().toolcommand('musicxml2ly')) elif t == '$filename': cmd.append(self._document) else: cmd.append(t) cmd.extend(['--output', '-']) return cmd def run_command(self): """ Run command line """ cmd = self.getCmd() directory = os.path.dirname(self._document) proc = subprocess.Popen(cmd, cwd=directory, universal_newlines=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdouterr = proc.communicate() return stdouterr def getPostSettings(self): """ returns settings in the post import tab """ post = [] for p in self.postChecks: post.append(p.isChecked()) return post def loadSettings(self): """ get users previous settings """ imp_default = [False, False, False, False, False] post_default = [True, False, False, True] s = QSettings() s.beginGroup('xml_import') for i, d in zip(self.impChecks, imp_default): i.setChecked(s.value(i.objectName(), d, bool)) for p, f in zip(self.postChecks, post_default): p.setChecked(s.value(p.objectName(), f, bool)) lang = s.value("language", "default", type("")) try: index = _langlist.index(lang) except ValueError: index = -1 self.langCombo.setCurrentIndex(index + 1) def saveSettings(self): """ save users last settings """ s = QSettings() s.beginGroup('xml_import') for i in self.impChecks: s.setValue(i.objectName(), i.isChecked()) for p in self.postChecks: s.setValue(p.objectName(), p.isChecked()) index = self.langCombo.currentIndex() s.setValue('language', 'default' if index == 0 else _langlist[index - 1])
class Dialog(toly_dialog.ToLyDialog): def __init__(self, parent=None): self.imp_prgm = "abc2ly" self.userg = "abc_import" self.nobeamCheck = QCheckBox() self.impChecks = [self.nobeamCheck] self.nobeamCheck.setObjectName("import-beaming") self.impExtra = [] super(Dialog, self).__init__(parent) app.translateUI(self) qutil.saveDialogSize(self, "abc_import/dialog/size", QSize(480, 160)) self.makeCommandLine() self.loadSettings() def translateUI(self): self.nobeamCheck.setText(_("Import beaming")) self.buttons.button(QDialogButtonBox.Ok).setText(_("Run abc2ly")) super(Dialog, self).translateUI() def makeCommandLine(self): """Reads the widgets and builds a command line.""" cmd = ["$abc2ly"] if self.nobeamCheck.isChecked(): cmd.append('-b') cmd.append("$filename") self.commandLine.setText(' '.join(cmd)) def run_command(self): """ABC import (at least for now) needs a specific solution here.""" cmd = self.getCmd('document.ly') directory = util.tempdir() subenviron = None if os.name == "nt": # Python 2.7 subprocess on Windows chokes on unicode in env subenviron = util.bytes_environ() else: subenviron = dict(os.environ) if sys.platform.startswith('darwin'): try: del subenviron['PYTHONHOME'] except KeyError: pass try: del subenviron['PYTHONPATH'] except KeyError: pass proc = subprocess.Popen(cmd, cwd=directory, env = subenviron, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE) stdouterr = proc.communicate() if not stdouterr[0]: try: with open(os.path.join(directory, cmd[-1])) as abc: stdouterr = (abc.read(), stdouterr[1]) except IOError: pass return stdouterr def loadSettings(self): """Get users previous settings.""" self.imp_default = [True] self.settings = QSettings() self.settings.beginGroup('abc_import') super(Dialog, self).loadSettings() def saveSettings(self): """Save users last settings.""" self.settings = QSettings() self.settings.beginGroup('abc_import') super(Dialog, self).saveSettings()
class ToLyDialog(QDialog): def __init__(self, parent=None): super(ToLyDialog, self).__init__(parent) self._info = None self._document = None self._path = None mainLayout = QGridLayout() self.setLayout(mainLayout) tabs = QTabWidget() import_tab = QWidget() post_tab = QWidget() itabLayout = QGridLayout(import_tab) ptabLayout = QGridLayout(post_tab) tabs.addTab(import_tab, self.imp_prgm) tabs.addTab(post_tab, "after import") self.formatCheck = QCheckBox() self.trimDurCheck = QCheckBox() self.removeScalesCheck = QCheckBox() self.runEngraverCheck = QCheckBox() self.postChecks = [ self.formatCheck, self.trimDurCheck, self.removeScalesCheck, self.runEngraverCheck ] self.versionLabel = QLabel() self.lilyChooser = lilychooser.LilyChooser() self.commandLineLabel = QLabel() self.commandLine = QTextEdit(acceptRichText=False) self.formatCheck.setObjectName("reformat") self.trimDurCheck.setObjectName("trim-durations") self.removeScalesCheck.setObjectName("remove-scaling") self.runEngraverCheck.setObjectName("engrave-directly") self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) userguide.addButton(self.buttons, self.userg) row = 0 for r, w in enumerate(self.impChecks): row += r itabLayout.addWidget(w, row, 0, 1, 2) w.toggled.connect(self.makeCommandLine) row += 1 for r, w in enumerate(self.impExtra): row += r itabLayout.addWidget(w, row, 0, 1, 2) itabLayout.addWidget(widgets.Separator(), row + 1, 0, 1, 2) itabLayout.addWidget(self.versionLabel, row + 2, 0, 1, 0) itabLayout.addWidget(self.lilyChooser, row + 3, 0, 1, 2) itabLayout.addWidget(widgets.Separator(), row + 4, 0, 1, 2) itabLayout.addWidget(self.commandLineLabel, row + 5, 0, 1, 2) itabLayout.addWidget(self.commandLine, row + 6, 0, 1, 2) ptabLayout.addWidget(self.formatCheck, 0, 0, 1, 2) ptabLayout.addWidget(self.trimDurCheck, 1, 0, 1, 2) ptabLayout.addWidget(self.removeScalesCheck, 2, 0, 1, 2) ptabLayout.addWidget(self.runEngraverCheck, 3, 0, 1, 2) ptabLayout.setRowStretch(4, 10) mainLayout.addWidget(tabs, 0, 0, 9, 2) mainLayout.addWidget(self.buttons, 10, 0, 1, 2) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) self.lilyChooser.currentIndexChanged.connect( self.slotLilyPondVersionChanged) self.slotLilyPondVersionChanged() def translateUI(self): self.versionLabel.setText(_("LilyPond version:")) self.commandLineLabel.setText(_("Command line:")) self.formatCheck.setText(_("Reformat source")) self.trimDurCheck.setText(_("Trim durations (Make implicit per line)")) self.removeScalesCheck.setText(_("Remove fraction duration scaling")) self.runEngraverCheck.setText(_("Engrave directly")) def setDocument(self, path): """Set the full path to the MusicXML document.""" self._document = path def slotLilyPondVersionChanged(self): self._info = self.lilyChooser.lilyPondInfo() def getCmd(self, outputname='-'): """Returns the command line.""" cmd = [] for t in self.commandLine.toPlainText().split(): if t == '$musicxml2ly': cmd.extend(self._info.toolcommand('musicxml2ly')) elif t == '$midi2ly': cmd.extend(self._info.toolcommand('midi2ly')) elif t == '$abc2ly': cmd.extend(self._info.toolcommand('abc2ly')) elif t == '$filename': cmd.append(self._document) else: cmd.append(t) cmd.extend(['--output', outputname]) return cmd def run_command(self): """Run command line.""" cmd = self.getCmd() directory = os.path.dirname(self._document) subenviron = None if os.name == "nt": # Python 2.7 subprocess on Windows chokes on unicode in env subenviron = util.bytes_environ() else: subenviron = dict(os.environ) if sys.platform.startswith('darwin'): try: del subenviron['PYTHONHOME'] except KeyError: pass try: del subenviron['PYTHONPATH'] except KeyError: pass proc = subprocess.Popen(cmd, cwd=directory, env=subenviron, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdouterr = proc.communicate() return stdouterr def getPostSettings(self): """Returns settings in the post import tab.""" post = [] for p in self.postChecks: post.append(p.isChecked()) return post def loadSettings(self): """Get users previous settings.""" post_default = [True, False, False, True] for i, d in zip(self.impChecks, self.imp_default): i.setChecked(self.settings.value(i.objectName(), d, bool)) for p, f in zip(self.postChecks, post_default): p.setChecked(self.settings.value(p.objectName(), f, bool)) def saveSettings(self): """Save users last settings.""" for i in self.impChecks: self.settings.setValue(i.objectName(), i.isChecked()) for p in self.postChecks: self.settings.setValue(p.objectName(), p.isChecked())
class Dialog(QDialog): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self._document = None self._path = None mainLayout = QGridLayout() self.setLayout(mainLayout) tabs = QTabWidget() import_tab = QWidget() post_tab = QWidget() itabLayout = QGridLayout(import_tab) ptabLayout = QGridLayout(post_tab) tabs.addTab(import_tab, "musicxml2ly") tabs.addTab(post_tab, "after import") self.noartCheck = QCheckBox() self.norestCheck = QCheckBox() self.nolayoutCheck = QCheckBox() self.nobeamCheck = QCheckBox() self.useAbsCheck = QCheckBox() self.commMidiCheck = QCheckBox() self.langCombo = QComboBox() self.langLabel = QLabel() self.impChecks = [self.noartCheck, self.norestCheck, self.nolayoutCheck, self.nobeamCheck, self.useAbsCheck, self.commMidiCheck] self.formatCheck = QCheckBox() self.trimDurCheck = QCheckBox() self.removeScalesCheck = QCheckBox() self.runEngraverCheck = QCheckBox() self.postChecks = [self.formatCheck, self.trimDurCheck, self.removeScalesCheck, self.runEngraverCheck] self.commandLineLabel = QLabel() self.commandLine = QTextEdit(acceptRichText=False) self.setChecksObjectNames() self.buttons = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) userguide.addButton(self.buttons, "musicxml_import") self.langCombo.addItem('') self.langCombo.addItems(_langlist) itabLayout.addWidget(self.noartCheck, 0, 0, 1, 2) itabLayout.addWidget(self.norestCheck, 1, 0, 1, 2) itabLayout.addWidget(self.nolayoutCheck, 2, 0, 1, 2) itabLayout.addWidget(self.nobeamCheck, 3, 0, 1, 2) itabLayout.addWidget(self.useAbsCheck, 4, 0, 1, 2) itabLayout.addWidget(self.commMidiCheck, 5, 0, 1, 2) itabLayout.addWidget(self.langLabel, 6, 0, 1, 2) itabLayout.addWidget(self.langCombo, 7, 0, 1, 2) itabLayout.addWidget(widgets.Separator(), 8, 0, 1, 2) itabLayout.addWidget(self.commandLineLabel, 9, 0, 1, 2) itabLayout.addWidget(self.commandLine, 10, 0, 1, 2) ptabLayout.addWidget(self.formatCheck, 0, 0, 1, 2) ptabLayout.addWidget(self.trimDurCheck, 1, 0, 1, 2) ptabLayout.addWidget(self.removeScalesCheck, 2, 0, 1, 2) ptabLayout.addWidget(self.runEngraverCheck, 3, 0, 1, 2) ptabLayout.setRowStretch(4, 10) mainLayout.addWidget(tabs, 0, 0, 9, 2) mainLayout.addWidget(self.buttons, 10, 0, 1, 2) app.translateUI(self) qutil.saveDialogSize(self, "xml_import/dialog/size", QSize(480, 260)) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) self.noartCheck.toggled.connect(self.makeCommandLine) self.norestCheck.toggled.connect(self.makeCommandLine) self.nolayoutCheck.toggled.connect(self.makeCommandLine) self.nobeamCheck.toggled.connect(self.makeCommandLine) self.useAbsCheck.toggled.connect(self.makeCommandLine) self.commMidiCheck.toggled.connect(self.makeCommandLine) self.langCombo.currentIndexChanged.connect(self.makeCommandLine) self.makeCommandLine() self.loadSettings() def setChecksObjectNames(self): self.noartCheck.setObjectName("articulation-directions") self.norestCheck.setObjectName("rest-positions") self.nolayoutCheck.setObjectName("page-layout") self.nobeamCheck.setObjectName("import-beaming") self.useAbsCheck.setObjectName("absolute-mode") self.commMidiCheck.setObjectName("comment-out-midi") self.formatCheck.setObjectName("reformat") self.trimDurCheck.setObjectName("trim-durations") self.removeScalesCheck.setObjectName("remove-scaling") self.runEngraverCheck.setObjectName("engrave-directly") def translateUI(self): self.setWindowTitle(app.caption(_("Import Music XML"))) self.noartCheck.setText(_("Import articulation directions")) self.norestCheck.setText(_("Import rest positions")) self.nolayoutCheck.setText(_("Import page layout")) self.nobeamCheck.setText(_("Import beaming")) self.useAbsCheck.setText(_("Pitches in absolute mode")) self.commMidiCheck.setText(_("Comment out midi block")) self.commandLineLabel.setText(_("Command line:")) self.langLabel.setText(_("Language for pitch names")) self.langCombo.setItemText(0, _("Default")) self.formatCheck.setText(_("Reformat source")) self.trimDurCheck.setText(_("Trim durations (Make implicit per line)")) self.removeScalesCheck.setText(_("Remove fraction duration scaling")) self.runEngraverCheck.setText(_("Engrave directly")) self.buttons.button(QDialogButtonBox.Ok).setText(_("Run musicxml2ly")) def setDocument(self, path): """Set the full path to the MusicXML document.""" self._document = path def makeCommandLine(self): """Reads the widgets and builds a command line.""" cmd = ["$musicxml2ly"] if self.useAbsCheck.isChecked(): cmd.append('-a') if not self.noartCheck.isChecked(): cmd.append('--nd') if not self.norestCheck.isChecked(): cmd.append('--nrp') if not self.nolayoutCheck.isChecked(): cmd.append('--npl') if not self.nobeamCheck.isChecked(): cmd.append('--no-beaming') if not self.commMidiCheck.isChecked(): cmd.append('-m') index = self.langCombo.currentIndex() if index > 0: cmd.append('--language=' + _langlist[index-1]) cmd.append("$filename") self.commandLine.setText(' '.join(cmd)) def getCmd(self): """Returns the command line.""" cmd = [] for t in self.commandLine.toPlainText().split(): if t == '$musicxml2ly': cmd.extend(lilypondinfo.preferred().toolcommand('musicxml2ly')) elif t == '$filename': cmd.append(self._document) else: cmd.append(t) cmd.extend(['--output', '-']) return cmd def run_command(self): """ Run command line """ cmd = self.getCmd() directory = os.path.dirname(self._document) proc = subprocess.Popen(cmd, cwd=directory, universal_newlines = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE) stdouterr = proc.communicate() return stdouterr def getPostSettings(self): """ returns settings in the post import tab """ post = [] for p in self.postChecks: post.append(p.isChecked()) return post def loadSettings(self): """ get users previous settings """ imp_default = [False, False, False, False, False, False] post_default = [True, False, False, True] s = QSettings() s.beginGroup('xml_import') for i, d in zip(self.impChecks, imp_default): i.setChecked(s.value(i.objectName(), d, bool)) for p, f in zip(self.postChecks, post_default): p.setChecked(s.value(p.objectName(), f, bool)) lang = s.value("language", "default", type("")) try: index = _langlist.index(lang) except ValueError: index = -1 self.langCombo.setCurrentIndex(index + 1) def saveSettings(self): """ save users last settings """ s = QSettings() s.beginGroup('xml_import') for i in self.impChecks: s.setValue(i.objectName(), i.isChecked()) for p in self.postChecks: s.setValue(p.objectName(), p.isChecked()) index = self.langCombo.currentIndex() s.setValue('language', 'default' if index == 0 else _langlist[index-1])
class AffectiveTypeForm(QDialog): def __init__(self, sid, parent=None): super(AffectiveTypeForm, self).__init__(parent) self.sid = sid ko = 0 layout1 = QGridLayout() try: details = self.pullDetails(self.sid) pagetitle = str(details['name']) + ' ' except: details = [] pagetitle = 'None' arr = self.pullClass(self.sid) print(arr) hold = {} for val in arr: grp = arr[val][2].split(':') self.num = val self.c = QCheckBox('cb' + str(val)) self.c.setText(arr[val][0] + ' - ' + arr[val][1]) self.c.setObjectName("chk" + str(val)) if (arr[val][3] == 0): self.c.setChecked(True) else: self.c.setChecked(False) self.c.toggled.connect( lambda state, x=val, y=self.c: self.chkFunc(x, y)) self.d = QPushButton() self.d.setObjectName("btnx" + str(val)) self.d.setText(grp[0] + ' to ' + grp[1]) self.d.setStyleSheet("background-color:" + grp[2] + "; color: white") #self.b = QPushButton() #self.b.setObjectName("btn"+str(val)) #self.b.setText('Terms') self.b1 = QPushButton() self.b1.setObjectName("btn1" + str(val)) self.b1.setText('Edit') hold["btn" + str(val)] = self.b1 layout1.addWidget(self.c, ko, 0) layout1.addWidget(self.d, ko, 1) layout1.addWidget(self.b1, ko, 2) ko += 1 for j in arr: self.h = j b = "btn" + str(j) self.connect(hold[b], SIGNAL("clicked()"), lambda gh=j: self.lunchEditForm(gh, self)) groupBox1 = QGroupBox('Attitude/Behavior') groupBox1.setLayout(layout1) self.pb = QPushButton() self.pb.setObjectName("Add") self.pb.setText("Add") self.pb1 = QPushButton() self.pb1.setObjectName("Cancel") self.pb1.setText("Cancel") hbo = QHBoxLayout() hbo.addWidget(self.pb1) hbo.addStretch() hbo.addWidget(self.pb) groupBox2 = QGroupBox('') groupBox2.setLayout(hbo) grid = QGridLayout() grid.addWidget(groupBox1, 0, 0) grid.addWidget(groupBox2, 1, 0) self.setLayout(grid) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.lunchAddForm(self.sid, self)) self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_close(self)) self.setWindowTitle(pagetitle) def chkFunc(self, a, b): # shost is a QString object self.a = a self.b = b g = Db() if b.isChecked() == True: y = {'active': 1} else: y = {'active': 0} z = {'id': self.a} j = g.update('datas', y, z) return j def pullClass(self, a): self.a = a cn = Db() datas = cn.selectn('datas', '', '', {'subID': self.a}) arr = {} try: for j in datas: arr[j['id']] = [ j['name'], j['abbrv'], j['description'], j['active'] ] except: pass return arr def pullDetails(self, a): self.a = a cn = Db() datas = cn.selectn('datas', '', 1, {'id': self.a}) return datas def lunchEditForm(self, a, b): b.close() self.a = a self.form = EditForm(self.a) self.form.show() def lunchAddForm(self, a, b): b.close() self.a = a self.form = AddForm(self.a) self.form.show() def lunchForm(self): self.form = super.AffectiveForm() self.form.show() def button_close(self, a): a.close() from frmaffective import AffectiveForm self.form = AffectiveForm() self.form.show()
def _create_widget(cls, c, parent, host=None): chb = QCheckBox(parent) chb.setObjectName(u'{0}_{1}'.format(cls._TYPE_PREFIX, c.name)) return chb
class NotificationWidget(QWidget): """Widget for notification phone numbers""" def __init__(self, name, default, parent=None): """ Initialise layout. Arguments: name - Name of the widget default - Default value for the widget parent - Parent widget Returns: None """ super(NotificationWidget, self).__init__(parent) # Global content self.name = name self.default = default if self.default == 'choose': self.edit = QComboBox(self) else: self.edit = QLineEdit(self.name, self) self.edit.setReadOnly(True) self.check_box = QCheckBox(self.name, self) # Event self.check_box.stateChanged.connect(self._change_state) # Layout layout = QHBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.check_box) layout.addWidget(self.edit) self.edit.setEnabled(False) # Default if self.default == 'choose': pass else: self.edit.setText(default) # Object name self.edit.setObjectName('noti_edit') self.check_box.setObjectName('noti_check') self.exceptions = [] @pyqtSlot() def _change_state(self): """ Change enable state of the edit Arguments: None Returns: None """ self.edit.setEnabled(self.check_box.isChecked()) def add_exceptions(self, name): """ Add a person to the exception list and dont send notification anymore. Arguments: name - Name of the person Returns: None """ self.exceptions.append(name) def update_combo_email(self, users): """ Update the combo boxes. Arguments: users - User dictionary Returns: None """ if self.default == 'choose': items = [ '@ {0}'.format(key) for key in users if '@ {0}'.format(key) not in self.exceptions ] self.edit.addItems(sorted(items)) def update_combo_telegram(self, users): """ Update the combo boxes. Arguments: users - User dictionary Returns: None """ if self.default == 'choose': items = [ 'T {0}'.format(key) for key in users if 'T {0}'.format(key) not in self.exceptions ] self.edit.addItems(sorted(items)) def clear_combo(self): """ Remove all users from the combo box. Arguments: None Returns: None """ if self.default == 'choose': self.edit.clear() def get_settings(self): """ Get text of the currently selected combo item. Arguments: None Returns: Settings dictionary """ settings = {} if self.default == 'choose': settings[self.name] = '{0}\t{1}'.format(self.edit.currentText(), self.check_box.isChecked()) else: settings[self.name] = '{0}\t{1}'.format(self.edit.text(), self.check_box.isChecked()) return settings def set_settings(self, name, state): """ Set currently selected combo item in text. Arguments: name - Name of the person that should be currently selected. state - State of the person (True/False;Enables/Disables) Returns: None """ self.check_box.setChecked(bool(state == 'True')) if self.default == 'choose': index = self.edit.findText(name) self.edit.setCurrentIndex(index) else: self.edit.setText(name)
def showPluginsSearchOptions(self): ''' Loads the search options of all the selected plugins and populates the relevant UI elements with input fields for the string options and checkboxes for the boolean options ''' pl = [] for pluginName in list( set([target['pluginName'] for target in self.ProjectWizardSelectedTargetsTable.targets])): plugin = self.PluginManager.getPluginByName(pluginName, 'Input') self.enabledPlugins.append(plugin) pl.append(plugin) ''' Build the configuration page from the available saerch options and add the page to the stackwidget ''' page = QWidget() page.setObjectName(_fromUtf8('searchconfig_page_' + plugin.name)) scroll = QScrollArea() scroll.setWidgetResizable(True) layout = QVBoxLayout() titleLabel = QLabel(_fromUtf8(plugin.name + self.trUtf8(' Search Options'))) layout.addWidget(titleLabel) vboxWidget = QWidget() vboxWidget.setObjectName(_fromUtf8('searchconfig_vboxwidget_container_' + plugin.name)) vbox = QGridLayout() vbox.setObjectName(_fromUtf8('searchconfig_vbox_container_' + plugin.name)) gridLayoutRowIndex = 0 ''' Load the String options first ''' pluginStringOptions = plugin.plugin_object.readConfiguration('search_string_options')[1] if pluginStringOptions: for idx, item in enumerate(pluginStringOptions.keys()): itemLabel = plugin.plugin_object.getLabelForKey(item) label = QLabel() label.setObjectName(_fromUtf8('searchconfig_string_label_' + item)) label.setText(itemLabel) vbox.addWidget(label, idx, 0) value = QLineEdit() value.setObjectName(_fromUtf8('searchconfig_string_value_' + item)) value.setText(pluginStringOptions[item]) vbox.addWidget(value, idx, 1) gridLayoutRowIndex = idx + 1 ''' Load the boolean options ''' pluginBooleanOptions = plugin.plugin_object.readConfiguration('search_boolean_options')[1] if pluginBooleanOptions: for idx, item in enumerate(pluginBooleanOptions.keys()): itemLabel = plugin.plugin_object.getLabelForKey(item) cb = QCheckBox(itemLabel) cb.setObjectName(_fromUtf8('searchconfig_boolean_label_' + item)) if pluginBooleanOptions[item] == 'True': cb.toggle() vbox.addWidget(cb, gridLayoutRowIndex + idx, 0) # If there are no search options just show a message if not pluginBooleanOptions and not pluginStringOptions: label = QLabel() label.setObjectName(_fromUtf8('no_search_config_options')) label.setText(self.trUtf8('This plugin does not offer any search options.')) vbox.addWidget(label, 0, 0) vboxWidget.setLayout(vbox) scroll.setWidget(vboxWidget) layout.addWidget(scroll) layout.addStretch(1) page.setLayout(layout) self.ui.searchConfiguration.addWidget(page) self.ui.searchConfiguration.setCurrentIndex(0) self.SearchConfigPluginConfigurationListModel = PluginConfigurationListModel(pl, self) self.SearchConfigPluginConfigurationListModel.checkPluginConfiguration() self.ui.personProjectWizardSearchConfigPluginsList.setModel(self.SearchConfigPluginConfigurationListModel) self.ui.personProjectWizardSearchConfigPluginsList.clicked.connect(self.changePluginConfigurationPage)
class previewDlg(QMainWindow): ''' classdocs ''' def __init__(self, parent, comp, basePMCheck, model): ''' Constructor ''' QMainWindow.__init__(self, parent) self.basePMCheck = basePMCheck # self.ui = Ui_Previewself.grbPageProperty() # self.ui.setupUi(self) self.resize(1000, 700) self.setWindowTitle("Preview Dialog") self.view = QgsComposerView(self) viewLayout = QGridLayout() viewLayout.setSpacing(0) viewLayout.setMargin(0) mHorizontalRuler = QgsComposerRuler(QgsComposerRuler.Horizontal) mVerticalRuler = QgsComposerRuler(QgsComposerRuler.Vertical) mRulerLayoutFix = QWidget() mRulerLayoutFix.setAttribute(Qt.WA_NoMousePropagation) mRulerLayoutFix.setBackgroundRole(QPalette.Window) mRulerLayoutFix.setFixedSize(mVerticalRuler.rulerSize(), mHorizontalRuler.rulerSize()) viewLayout.addWidget(mRulerLayoutFix, 0, 0) viewLayout.addWidget(mHorizontalRuler, 0, 1) viewLayout.addWidget(mVerticalRuler, 1, 0) self.view.setContentsMargins(0, 0, 0, 0) self.view.setHorizontalRuler(mHorizontalRuler) self.view.setVerticalRuler(mVerticalRuler) viewLayout.addWidget(self.view, 1, 1) # self.scene = comp self.view.setZoomLevel(1.0) self.view.setComposition(comp) self.scene = self.view.composition() layout = QVBoxLayout() hLayout = QHBoxLayout() hLayout.addLayout(viewLayout) self.mapItem = self.scene.getComposerMapById(0) self.view.scale(2.8, 2.8) self.view.setPreviewModeEnabled(True) self.toolBarAction = self.addToolBar("composer action") self.actionMapRefresh = QAction(self) self.actionMapRefresh.setObjectName("actionMapRefresh") icon3 = QIcon("Resource/Refresh.png") self.actionMapRefresh.setIcon(icon3) self.actionMapRefresh.setToolTip("Refresh") # self.textItemAction.setCheckable(True) self.connect(self.actionMapRefresh, SIGNAL("triggered()"), self.actionMapRefresh_triggered) self.toolBarAction.addAction(self.actionMapRefresh) # # self.templeteCreateAction = QAction(self) # # self.templeteCreateAction.setObjectName("createTempleteAction") # # icon4 = QIcon("Resource\\templetepointer.png") # # self.templeteCreateAction.setIcon(icon4) # # self.templeteCreateAction.setToolTip("Create Templete") # # self.templeteCreateAction.setCheckable(True) # # self.connect(self.templeteCreateAction, SIGNAL("triggered()"), self.createTempleteAction) # # self.toolBar.addAction(self.templeteCreateAction) # layout.insertWidget(0, self.toolBar) # self.scene.selectedItemChanged.connect(self.selectedItemDisplay) self.view.selectedItemChanged.connect(self.selectedItemDisplay) self.view.cursorPosChanged.connect(self.cursorPosChangedEvent) # self.connect(self.view, SIGNAL("selectedItemChanged(QgsComposerItem)"),self, SLOT("selectedItemDisplay(QgsComposerItem)")) # self.scene.composerLabelAdded.connect(self.composerLabelAddedEvent) self.view.itemRemoved.connect(self.deleteItem) # self.connect( self.view, SIGNAL( "actionFinished()" ), self.setSelectionTool) #listen out for position updates from the QgsComposerView self.propertyWidget = QWidget(self) hLayout.addWidget(self.propertyWidget) self.propertyWidget.setObjectName("propertyWidget") self.propertyWidget.resize(222, 302) self.vLayout_3 = QVBoxLayout(self.propertyWidget) self.vLayout_3.setObjectName("vLayout_3") self.groupBox = QGroupBox(self.propertyWidget) self.groupBox.setObjectName("groupBox") self.horizontalLayout_2 = QHBoxLayout(self.groupBox) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.frame = QFrame(self.groupBox) self.frame.setFrameShape(QFrame.StyledPanel) self.frame.setFrameShadow(QFrame.Raised) self.frame.setObjectName("frame") self.verticalLayout = QVBoxLayout(self.frame) self.verticalLayout.setObjectName("verticalLayout") self.label = QLabel(self.frame) self.label.setObjectName("label") self.verticalLayout.addWidget(self.label) self.labelText = QPlainTextEdit(self.frame) self.labelText.setObjectName("labelText") self.verticalLayout.addWidget(self.labelText) self.btnLabelFont = QPushButton(self.frame) self.btnLabelFont.setObjectName("btnLabelFont") self.verticalLayout.addWidget(self.btnLabelFont) self.btnLabelColor = QPushButton(self.frame) self.btnLabelColor.setObjectName("btnLabelColor") self.verticalLayout.addWidget(self.btnLabelColor) self.frame_2 = QFrame(self.frame) self.frame_2.setFrameShape(QFrame.StyledPanel) self.frame_2.setFrameShadow(QFrame.Raised) self.frame_2.setObjectName("frame_2") self.horizontalLayout = QHBoxLayout(self.frame_2) self.horizontalLayout.setObjectName("horizontalLayout") self.label_2 = QLabel(self.frame_2) self.label_2.setObjectName("label_2") self.horizontalLayout.addWidget(self.label_2) self.spinLabelRotation = QSpinBox(self.frame_2) self.spinLabelRotation.setObjectName("spinLabelRotation") self.spinLabelRotation.setMinimum(-360) self.spinLabelRotation.setMaximum(360) self.horizontalLayout.addWidget(self.spinLabelRotation) self.verticalLayout.addWidget(self.frame_2) self.chbBackgroundEnable = QCheckBox(self.frame) self.chbBackgroundEnable.setChecked(True) self.chbBackgroundEnable.setObjectName("chbBackgroundEnable") self.verticalLayout.addWidget(self.chbBackgroundEnable) self.horizontalLayout_2.addWidget(self.frame) self.vLayout_3.addWidget(self.groupBox) self.resolutionFrame = QFrame(self.frame) self.resolutionFrame.setFrameShape(QFrame.StyledPanel) self.resolutionFrame.setFrameShadow(QFrame.Raised) self.resolutionFrame.setObjectName("resolutionFrame") self.horizontalLayout4 = QHBoxLayout(self.resolutionFrame) self.horizontalLayout4.setObjectName("horizontalLayout4") self.label_resolution = QLabel(self.resolutionFrame) self.label_resolution.setObjectName("label_resolution") self.label_resolution.setText("Print Resolution (dpi):") self.horizontalLayout4.addWidget(self.label_resolution) self.spinResolution = QSpinBox(self.resolutionFrame) self.spinResolution.setObjectName("spinResolution") self.spinResolution.setMinimum(0) self.spinResolution.setMaximum(1000) self.spinResolution.setValue(300) self.horizontalLayout4.addWidget(self.spinResolution) # self.verticalLayout.addWidget(self.frame_2) self.vLayout_3.addWidget(self.resolutionFrame) self.gbTable = GroupBox(self.propertyWidget) self.gbTable.Caption = "Table" self.vLayout_3.addWidget(self.gbTable) self.mTableView = QTableView(self.gbTable) self.gbTable.Add = self.mTableView hHeder = self.mTableView.horizontalHeader() hHeder.setVisible(False) vHeder = self.mTableView.verticalHeader() vHeder.setVisible(False) # self.mTableView.setFixedHeight(70) # self.mTableView.setFixedWidth(comp.paperWidth() - 40) # self.stdItemModel = QStandardItemModel() # self. self.spaceItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.vLayout_3.addItem(self.spaceItem) self.groupBox.setTitle("Label Property") self.label.setText("Label Text:") self.btnLabelFont.setText("Label Font") self.btnLabelColor.setText("Label Color") self.label_2.setText("Label Rotation:") self.chbBackgroundEnable.setText("Background Enable") self.groupBox.setEnabled(False) self.connect(self.btnLabelFont, SIGNAL("clicked()"), self.btnLabelFontClick) self.connect(self.btnLabelColor, SIGNAL("clicked()"), self.btnLabelColorClick) self.connect(self.chbBackgroundEnable, SIGNAL("clicked()"), self.chbBackgroundEnableClick) self.labelText.textChanged.connect(self.labelTextChanged) self.spinLabelRotation.valueChanged.connect( self.spinLabelRotationValueChanged) layout.addLayout(hLayout) # self.btnBack = QPushButton() self.btnBack.setText("back") footerLayout = QHBoxLayout() footerLayout.addWidget(self.btnBack) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") footerLayout.addWidget(self.buttonBox) layout.addLayout(footerLayout) self.setLayout(layout) deleteItemKey = QShortcut(QKeySequence(Qt.Key_Delete), self) deleteItemKey.activated.connect(self.deleteItem) # self.btnBack.clicked.connect(self.back) self.connect(self.buttonBox, SIGNAL("accepted()"), self.acceptMethod) self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject) self.btnCancel = self.buttonBox.button(QDialogButtonBox.Cancel) self.view.setCurrentTool(QgsComposerView.Select) self.btnLabelColor.setVisible(False) # self.btnBack.setVisible(False) self.chbBackgroundEnable.setVisible(False) # self.view.emit(SIGNAL("actionFinished")) # if self.scene.plotStyle() != QgsComposition.Preview: # self.scene.setPlotStyle(QgsComposition.Preview) # self.mapItem.setPreviewMode(QgsComposerMap.Render) # self.mapItem.updateCachedImage() # self.mapItem.setSelected(True) self.mComposition = comp self.composerMapItem = self.mComposition.composerMapItems()[0] self.composerMapItem.setUpdatesEnabled(True) self.mStdModel = model self.mTableView.setModel(self.mStdModel) self.mTableView.setSpan(0, 0, 1, 6) self.mTableView.setSpan(1, 0, 1, 2) self.mTableView.setSpan(2, 0, 2, 1) self.mTableView.setSpan(4, 0, 1, 2) self.mTableView.setSpan(5, 0, 1, 2) self.mTableView.setSpan(6, 0, 1, 2) self.mTableView.setSpan(0, 6, 1, 8) self.mTableView.setSpan(1, 7, 1, 4) self.mTableView.setSpan(1, 11, 1, 3) self.mTableView.setSpan(2, 7, 1, 4) self.mTableView.setSpan(2, 11, 1, 3) def acceptMethod(self): # self.mStdModel.setItem(0, QStandardItem("nnnnnnnn")) filePath = QFileDialog.getSaveFileName( self, "Save PDF File", QCoreApplication.applicationDirPath(), "pdf files(*.pdf )") if filePath == "": return self.mComposition.clearSelection() self.mComposition.setPrintResolution(self.spinResolution.value()) resultPdf = self.mComposition.exportAsPDF(filePath) if resultPdf: message = QMessageBox.information(self, "Result", "Successful export PDF") else: message = QMessageBox.information(self, "Result", "Don't export PDF") def rePresent(self, comp, model): self.mComposition = comp self.mStdModel = model self.view.setComposition(comp) self.scene = self.view.composition() def back(self): self.done(2) def spinLabelRotationValueChanged(self, rotationValue): self.selectedLabelItem.setItemRotation(rotationValue) def cursorPosChangedEvent(self, scenePointF): self.scenePoint = scenePointF # i = 100 def labelTextChanged(self): self.selectedLabelItem.beginCommand( "Label text changed", QgsComposerMergeCommand.ComposerLabelSetText) self.selectedLabelItem.blockSignals(True) self.selectedLabelItem.setText(self.labelText.toPlainText()) self.selectedLabelItem.update() self.selectedLabelItem.blockSignals(False) self.selectedLabelItem.endCommand() def chbBackgroundEnableClick(self): if self.chbBackgroundEnable.isChecked(): self.selectedLabelItem.setBackgroundEnabled(True) self.mapItem.updateCachedImage() else: self.selectedLabelItem.setBackgroundEnabled(False) self.mapItem.updateCachedImage() def btnLabelFontClick(self): dlgFont = QFontDialog(self) dlgFont.setCurrentFont(self.selectedLabelItem.font()) result = dlgFont.exec_() if result == 1: self.labelFont = dlgFont.selectedFont() else: self.labelFont = QFont() self.selectedLabelItem.setFont(self.labelFont) def btnLabelColorClick(self): dlgColor = QColorDialog(self) dlgColor.setCurrentColor(self.selectedLabelItem.fontColor()) result = dlgColor.exec_() if result == 1: self.labelColor = dlgColor.selectedColor() self.selectedLabelItem.setFontColor(self.labelColor) def createTempleteAction(self): if self.templeteCreateAction.isChecked() and self.basePMCheck: font = QFont("Arial", 13) font.setItalic(True) self.compLabel1 = QgsComposerLabel(self.scene) self.compLabel1.setFont(font) self.compLabel1.setText("South China Sea") self.compLabel1.setBackgroundEnabled(False) self.compLabel1.setItemPosition(156, 100) self.compLabel1.adjustSizeToText() self.compLabel1.setItemRotation(60) # mapitem = self.scene.composerMapItems() # mapitem[0].addItem(self.compLabel1) self.scene.addItem(self.compLabel1) self.compLabel2 = QgsComposerLabel(self.scene) self.compLabel2.setFont(font) self.compLabel2.setText("Straits Of Malacca") self.compLabel2.setBackgroundEnabled(False) self.compLabel2.setItemPosition(35, 100) self.compLabel2.adjustSizeToText() self.compLabel2.setItemRotation(60) self.scene.addItem(self.compLabel2) font.setItalic(False) self.compLabel3 = QgsComposerLabel(self.scene) self.compLabel3.setFont(font) self.compLabel3.setBackgroundEnabled(False) self.compLabel3.setText("THAILAND") self.compLabel3.setItemPosition(68, 60) self.compLabel3.adjustSizeToText() # self.compLabel3.setItemRotation(0.5) self.scene.addItem(self.compLabel3) # self.templeteCreateAction.setChecked(False) self.compLabel4 = QgsComposerLabel(self.scene) self.compLabel4.setFont(font) self.compLabel4.setBackgroundEnabled(False) self.compLabel4.setText("SINGAPORE") self.compLabel4.setItemPosition(141, 218) self.compLabel4.adjustSizeToText() # self.compLabel3.setItemRotation(0.5) self.scene.addItem(self.compLabel4) self.templeteCreateAction.setChecked(False) self.compLabel4.setSelected(True) elif self.templeteCreateAction.isChecked( ) and self.basePMCheck == False: font = QFont("Arial", 14) font.setItalic(True) self.compLabel5 = QgsComposerLabel(self.scene) self.compLabel5.setFont(font) self.compLabel5.setText("South China Sea") self.compLabel5.setBackgroundEnabled(False) self.compLabel5.setItemPosition(108, 86) self.compLabel5.adjustSizeToText() self.compLabel5.setItemRotation(-45) # mapitem = self.scene.composerMapItems() # mapitem[0].addItem(self.compLabel1) self.scene.addItem(self.compLabel5) self.compLabel6 = QgsComposerLabel(self.scene) self.compLabel6.setFont(font) self.compLabel6.setText("Sulu Sea") self.compLabel6.setBackgroundEnabled(False) self.compLabel6.setItemPosition(236, 38) self.compLabel6.adjustSizeToText() self.compLabel6.setItemRotation(45) self.scene.addItem(self.compLabel6) font.setItalic(False) self.compLabel7 = QgsComposerLabel(self.scene) self.compLabel7.setFont(font) self.compLabel7.setBackgroundEnabled(False) self.compLabel7.setText("Celebes Sea") self.compLabel7.setItemPosition(242, 112) self.compLabel7.adjustSizeToText() self.compLabel7.setItemRotation(-45) # self.compLabel3.setItemRotation(0.5) self.scene.addItem(self.compLabel7) # self.templeteCreateAction.setChecked(False) self.compLabel8 = QgsComposerLabel(self.scene) self.compLabel8.setFont(font) self.compLabel8.setBackgroundEnabled(False) self.compLabel8.setText("INDONESIA\n(Kalimantan)") self.compLabel8.setItemPosition(172, 148, 32, 16) # self.compLabel8.setHAlign(Qt.AlignHCenter) # self.compLabel8.setVAlign(Qt.AlignVCenter) # self.compLabel8.setFrameEnabled(False) # self.compLabel8.setItemPosition() # self.compLabel8.adjustSizeToText() # self.compLabl3.setItemRotation(0.5) self.scene.addItem(self.compLabel8) self.compLabel9 = QgsComposerLabel(self.scene) self.compLabel9.setFont(font) self.compLabel9.setBackgroundEnabled(False) self.compLabel9.setText("BRUNEI") self.compLabel9.setItemPosition(136, 83) self.compLabel9.adjustSizeToText() # self.compLabl3.setItemRotation(0.5) self.scene.addItem(self.compLabel9) self.templeteCreateAction.setChecked(False) pass def actionMapRefresh_triggered(self): self.view.setCurrentTool(QgsComposerView.AddRectangle) def setSelectionTool(self): self.view.deleteSelectedItems() font = QFont("Arial", 14) newLabelItem = QgsComposerLabel(self.scene) newLabelItem.setText("QGIS") newLabelItem.setFont(font) newLabelItem.setItemPosition(self.scenePoint.x(), self.scenePoint.y()) newLabelItem.adjustSizeToText() self.scene.addItem(newLabelItem) # selectItemPoint = self.scene.composerItemAt(self.scenePoint) newLabelItem.setSelected(True) self.groupBox.setEnabled(True) self.selectedLabelItem = newLabelItem # txt = self.selectedLabelItem.text() # textDoc = QTextDocument(txt) self.labelText.setPlainText(self.selectedLabelItem.text()) # self.scene.setSelectedItem(self.newLabelItem) self.view.setCurrentTool(QgsComposerView.Select) # self.selectedLabelItem = self.view.currentTool() self.textItemAction.setChecked(False) def selectedItemDisplay(self, item): if self.scene.plotStyle() != QgsComposition.Preview: self.scene.setPlotStyle(QgsComposition.Preview) self.mapItem.setPreviewMode(QgsComposerMap.Render) self.mapItem.updateCachedImage() item._class_ = QgsComposerLabel # selectedItems = self.scene.selectedComposerItems(True) # if isinstance(item, QgsComposerItem): # self.selectedLabelItem = item # if isinstance(item, QGraphicsRectItem): # self.selectedLabelItem = item if isinstance(item, QgsComposerLabel): self.selectedLabelItem = item self.groupBox.setEnabled(True) self.labelText.setPlainText(self.selectedLabelItem.text()) self.spinLabelRotation.setValue(self.selectedLabelItem.rotation()) else: self.groupBox.setEnabled(False) # print "debug" itemName = self.view.currentTool() if itemName == 5: item.setText("label") pass def deleteItem(self): self.view.deleteSelectedItems()
def addCheckBox(self, name): cb = QCheckBox(self) cb.setText("") cb.setObjectName(name) return cb
class FlightPlanBaseDlg(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) palette = QPalette(); brush = QBrush(QColor(255, 255, 255, 255)); brush.setStyle(Qt.SolidPattern); palette.setBrush(QPalette.Active, QPalette.Base, brush); palette.setBrush(QPalette.Active, QPalette.Window, brush); palette.setBrush(QPalette.Inactive, QPalette.Base, brush); palette.setBrush(QPalette.Inactive, QPalette.Window, brush); palette.setBrush(QPalette.Disabled, QPalette.Base, brush); palette.setBrush(QPalette.Disabled, QPalette.Window, brush); self.setPalette(palette); self.ui = Ui_FlightPlannerBase() self.ui.setupUi(self) self.newDlgExisting = False self.chbHideCloseInObst = QCheckBox(self.ui.grbResult) font = QFont() font.setBold(False) font.setWeight(50) self.chbHideCloseInObst.setFont(font) self.chbHideCloseInObst.setObjectName("chbHideCloseInObst") self.ui.vlResultGroup.addWidget(self.chbHideCloseInObst) self.chbHideCloseInObst.setText("Hide close-in obstacles") self.chbHideCloseInObst.setVisible(False) self.ui.tblHistory.setSelectionBehavior(1) # self.ui.tabCtrlGeneral.setTabsClosable(True) self.ui.btnUpdateQA.setVisible(False) self.ui.btnUpdateQA_2.setVisible(False) ''' combo boxes event ''' self.ui.cmbObstSurface.currentIndexChanged.connect(self.cmbObstSurfaceChanged) self.ui.cmbUnits.currentIndexChanged.connect(self.changeResultUnit) ''' buttons clicked connect ''' self.ui.btnClose.clicked.connect(self.reject) self.ui.btnClose_2.clicked.connect(self.reject) self.ui.btnHistoryClose.clicked.connect(self.reject) self.ui.btnConstruct.clicked.connect(self.btnConstruct_Click) self.ui.btnEvaluate.clicked.connect(self.btnEvaluate_Click) self.ui.btnOpenData.clicked.connect(self.openData) self.ui.btnSaveData.clicked.connect(self.saveData) self.ui.btnPDTCheck.clicked.connect(self.btnPDTCheck_Click) self.ui.btnExportResult.clicked.connect(self.exportResult) self.ui.tblHistory.clicked.connect(self.tblHistory_Click) self.ui.btnUpdateQA.clicked.connect(self.btnUpdateQA_Click) self.ui.btnUpdateQA_2.clicked.connect(self.btnUpdateQA_2_Click) self.ui.btnCriticalLocate.clicked.connect(self.criticalLocate) self.connect(self.ui.tblObstacles, SIGNAL("tableViewObstacleMouseReleaseEvent_rightButton"), self.tableViewObstacleMouseTeleaseEvent_rightButton) self.connect(self.ui.tblObstacles, SIGNAL("pressedEvent"), self.tblObstacles_pressed) ''' properties ''' self.parametersPanel = None self.obstaclesModel = None self.surfaceType = "" self.surfaceSubGroupNames = [] self.uiStateInit() self.obstacleTableInit() self.newDlgExisting = True self.resultColumnNames = [] self.stdItemModelHistory = QStandardItemModel() # self.stdItemModelHistory. self.ui.tblHistory.setModel(self.stdItemModelHistory) icon = QIcon() icon.addPixmap(QPixmap("Resource/btnImage/dlgIcon.png"), QIcon.Normal, QIcon.Off) self.setWindowIcon(icon) self.resultLayerList = [] self.symbolLayers = [] self.selectedObstacleMoselIndex = None self.changedCriticalObstacleValue = [] def tblObstacles_pressed(self, modelIndex): self.selectedObstacleMoselIndex = modelIndex def tableViewObstacleMouseTeleaseEvent_rightButton(self, e): if self.obstaclesModel == None: return featID = self.obstaclesModel.data(self.obstaclesModel.index(self.selectedObstacleMoselIndex.row(), self.obstaclesModel.IndexObjectId)).toString() layerID = self.obstaclesModel.data(self.obstaclesModel.index(self.selectedObstacleMoselIndex.row(), self.obstaclesModel.IndexLayerId)).toString() name = self.obstaclesModel.data(self.obstaclesModel.index(self.selectedObstacleMoselIndex.row(), self.obstaclesModel.IndexName)).toString() xValue = self.obstaclesModel.data(self.obstaclesModel.index(self.selectedObstacleMoselIndex.row(), self.obstaclesModel.IndexX)).toString() yValue = self.obstaclesModel.data(self.obstaclesModel.index(self.selectedObstacleMoselIndex.row(), self.obstaclesModel.IndexY)).toString() altitudeMValue = self.obstaclesModel.data(self.obstaclesModel.index(self.selectedObstacleMoselIndex.row(), self.obstaclesModel.IndexAltM)).toString() surfaceName = self.obstaclesModel.data(self.obstaclesModel.index(self.selectedObstacleMoselIndex.row(), self.obstaclesModel.IndexSurface)).toString() ocaMValue = self.obstaclesModel.data(self.obstaclesModel.index(self.selectedObstacleMoselIndex.row(), self.obstaclesModel.IndexOcaM)).toString() # ocaMValue = self.obstaclesModel.data(self.obstaclesModel.index(self.selectedObstacleMoselIndex.row(), self.obstaclesModel.IndexOcaM)).toString() obstacle = Obstacle(name, Point3D(float(xValue), float(yValue), float(altitudeMValue)), layerID, featID, None, 0.0, self.obstaclesModel.MocMultiplier, 0.0) self.changedCriticalObstacleValue = {"Obstacle": obstacle, "SurfaceName": surfaceName, "OcaM": float(ocaMValue) if ocaMValue != "" else None} menu = QMenu() actionSetCriticalObst = QgisHelper.createAction(menu, "Set Most Critical Obstacles", self.menuSetCriticalObstClick) menu.addAction( actionSetCriticalObst ) menu.exec_( self.ui.tblObstacles.mapToGlobal(e.pos() )) def menuSetCriticalObstClick(self): pass # OasObstacles.resultCriticalObst.Obstacle = self.changedCriticalObstacleValue["Obstacle"] # OasObstacles.resultCriticalObst.Surface = self.changedCriticalObstacleValue["SurfaceName"] # OasObstacles.resultCriticalObst.Assigned = True # ocaMValue = self.changedCriticalObstacleValue["OcaM"] # # OasObstacles.resultOCA = Altitude(float(ocaMValue) if ocaMValue != "" else None) # if OasObstacles.resultOCA == None: # OasObstacles.resultOCH = None # else: # OasObstacles.resultOCH = OasObstacles.resultOCA - self.ui.pnlThr.Altitude() # # point3d = self.ui.pnlThr.Point3d # num = Unit.ConvertDegToRad(float(self.ui.txtTrack.Value)) # num1 = self.method_40() # zC = OasObstacles.constants.ZC / OasObstacles.constants.ZA # point3d1 = MathHelper.distanceBearingPoint(point3d, num, zC) # metres2 = OasObstacles.resultCriticalObst.method_2(point3d).Metres # z = metres2 - point3d.z() # num3 = math.tan(Unit.ConvertDegToRad(num1)) # num4 = z / num3 # OasObstacles.resultSocPosition = MathHelper.distanceBearingPoint(point3d1, num + 3.14159265358979, num4).smethod_167(0) # if (num4 > zC): # OasObstacles.resultSocText = Messages.X_BEFORE_THRESHOLD % (num4 - zC) # else: # OasObstacles.resultSocText = Messages.X_PAST_THRESHOLD % (zC - num4) # self.setCriticalObstacle() def criticalLocate(self): point = None try: point = QgsPoint(float(self.ui.txtCriticalX.text()), float(self.ui.txtCriticalY.text())) except: return if define._units == QGis.Meters: extent = QgsRectangle(point.x() - 350, point.y() - 350, point.x() + 350, point.y() + 350) else: extent = QgsRectangle(point.x() - 0.005, point.y() - 0.005, point.x() + 0.005, point.y() + 0.005) if extent is None: return QgisHelper.zoomExtent(point, extent, 2) def trackRadialPanelSetEnabled(self): positionPanels = self.findChildren(PositionPanel) if len(positionPanels) > 0: flag = False for pnl in positionPanels: if pnl.IsValid(): flag = True break trPanels = self.findChildren(TrackRadialBoxPanel) if len(trPanels) > 0: for pnl in trPanels: pnl.Enabled = flag def setDataInHistoryModel(self, dataList, newFlag = False): # dataList is list of list of tuple with name and data # example # dataList = [ list of name, list of data ] # dataList = [["lat", "lon"], ["59", "17"]] if newFlag: self.stdItemModelHistory.setHorizontalHeaderLabels(dataList[0][0]) for i in range(len(dataList)): for j in range(len(dataList[i][1])): item = QStandardItem(dataList[i][1][j]) item.setEditable(False) self.stdItemModelHistory.setItem(i, j, item) return if len(dataList) > 0: rowcount = self.stdItemModelHistory.rowCount() if self.stdItemModelHistory.rowCount() > 0: for i in range(len(dataList[1])): item = QStandardItem(dataList[1][i]) item.setEditable(False) self.stdItemModelHistory.setItem(rowcount, i, item) pass else: self.stdItemModelHistory.setHorizontalHeaderLabels(dataList[0]) for i in range(len(dataList[1])): item = QStandardItem(dataList[1][i]) item.setEditable(False) self.stdItemModelHistory.setItem(0, i, item) def btnPDTCheck_Click(self): pass def cmbObstSurfaceChanged(self): if self.obstaclesModel != None: if self.ui.cmbObstSurface.currentIndex() == 0 and self.ui.cmbObstSurface.currentText() == "All": self.obstaclesModel.setFilterFixedString("") else: self.obstaclesModel.setFilterFixedString(self.ui.cmbObstSurface.currentText()) def obstacleTableInit(self): self.ui.tblObstacles.setSelectionBehavior(QAbstractItemView.SelectRows) self.ui.tblObstacles.setSortingEnabled(True) def uiStateInit(self): self.ui.cmbUnits.addItems([Captions.METRES, Captions.FEET]) self.ui.cmbUnits.setCurrentIndex(1) self.ui.cmbUnits.currentIndexChanged.connect(self.changeResultUnit) pass def tblHistory_Click(self, modelIndex): pass def btnConstruct_Click(self): # qgsLayerTreeView = define._mLayerTreeView # groupName = self.surfaceType # layerTreeModel = qgsLayerTreeView.layerTreeModel() # layerTreeGroup = layerTreeModel.rootGroup() # rowCount = layerTreeModel.rowCount() # groupExisting = False # if rowCount > 0: # for i in range(rowCount): # qgsLayerTreeNode = layerTreeModel.index2node(layerTreeModel.index(i, 0)) # if qgsLayerTreeNode.nodeType() == 0: # qgsLayerTreeNode._class_ = QgsLayerTreeGroup # if isinstance(qgsLayerTreeNode, QgsLayerTreeGroup) and qgsLayerTreeNode.name() == groupName: # groupExisting = True # # if groupExisting: # if len(self.resultLayerList) > 0: # QgisHelper.removeFromCanvas(define._canvas, self.resultLayerList) # self.resultLayerList = [] # else: # QMessageBox.warning(self, "Warning", "Please remove \"" + self.surfaceType + "\" layer group from LayerTreeView.") # return False self.resultLayerList = [] return True def btnUpdateQA_Click(self): pass def btnUpdateQA_2_Click(self): pass def btnEvaluate_Click(self): try: if self.obstaclesModel == None: self.initObstaclesModel() if self.obstaclesModel == None: return surfaceLayers = QgisHelper.getSurfaceLayers(self.surfaceType, self.surfaceSubGroupNames) self.initObstaclesModel() self.obstaclesModel.loadObstacles(surfaceLayers) self.obstaclesModel.setLocateBtn(self.ui.btnLocate) self.ui.tblObstacles.setModel(self.obstaclesModel) self.obstaclesModel.setTableView(self.ui.tblObstacles) self.obstaclesModel.setHiddenColumns(self.ui.tblObstacles) self.ui.tabCtrlGeneral.setCurrentIndex(1) if self.ui.cmbObstSurface.isVisible(): self.ui.cmbObstSurface.clear() self.initSurfaceCombo() self.ui.cmbObstSurface.setCurrentIndex(0) self.ui.btnExportResult.setEnabled(True) self.setResultPanel() except UserWarning as e: QMessageBox.warning(self, "Information", e.message) def initParametersPan(self): parametersPanelWidget = QWidget(self) # self.parametersPanel = uiObject if self.parametersPanel != None: self.parametersPanel.setupUi(parametersPanelWidget) self.ui.vlScrollWidget.addWidget(parametersPanelWidget) lstTextControls = self.ui.grbGeneral.findChildren(QLineEdit) for ctrl in lstTextControls: ctrl.textChanged.connect(self.initResultPanel) lstComboControls = self.ui.grbGeneral.findChildren(QComboBox) for ctrl in lstComboControls: ctrl.currentIndexChanged.connect(self.initResultPanel) # lstTextControls = self.findChildren(QLineEdit) # for ctrl in lstTextControls: # ctrl.setMinimumWidth(100) # ctrl.setMaximumWidth(100) # lstComboControls = self.findChildren(QComboBox) # for ctrl in lstComboControls: # ctrl.setMinimumWidth(100) # ctrl.setMaximumWidth(100) # newWidth = int(define._appWidth / float(1280) * parametersPanelWidget.width()) # newHeight = int(define._appHeight / float(800) * parametersPanelWidget.height()) # if newWidth > define._appWidth: # newWidth -= 50 # if newHeight > define._appHeight: # newHeight -= 50 # parametersPanelWidget.resize(newWidth, newHeight) def initResultPanel(self): if self.obstaclesModel != None and self.ui.btnEvaluate.isEnabled(): self.obstaclesModel.clear() lstTextControls = self.ui.grbResult.findChildren(QLineEdit) for ctrl in lstTextControls: if ctrl.objectName() == "txtOCH" or ctrl.objectName() == "txtOCA": continue ctrl.setText("") self.ui.btnExportResult.setDisabled(True) # self.ui.btnEvaluate.setEnabled(False) def initObstaclesModel(self): pass def initSurfaceCombo(self): pass def setResultPanel(self): pass def saveData(self): try: filePathDir = QFileDialog.getSaveFileName(self, "Save Input Data",QCoreApplication.applicationDirPath (),"Xml Files(*.xml)") if filePathDir == "": return DataHelper.saveInputParameters(filePathDir, self) # contents = None # with open(filePathDir, 'rb', 0) as tempFile: # contents = tempFile.read() # tempFile.flush() # tempFile.close() # bytes = FasDataBlockFile.CRC_Calculation(contents) # string_0 = QString(filePathDir) # path = string_0.left(string_0.length() - 3) + "crc" # fileStream = open(path, 'wb') # fileStream.write(bytes) # fileStream.close() return filePathDir except UserWarning as e: QMessageBox.warning(self, "Error", e.message) def openData(self): try: filePathDir = QFileDialog.getOpenFileName(self, "Open Input Data",QCoreApplication.applicationDirPath (),"Xml Files(*.xml)") if filePathDir == "": return layers = define._canvas.layers() if layers != None and len(layers) > 0: for layer in layers: if layer.name() == "Symbols": self.currentLayer = layer try: self.initAerodromeAndRwyCmb() except: pass try: self.initBasedOnCmb() except: pass break # contents = None # with open(filePathDir, 'rb', 0) as tempFile: # contents = tempFile.read() # tempFile.close() # bytes = FasDataBlockFile.CRC_Calculation(contents) # # string_0 = QString(filePathDir) # crcFileDir = string_0.left(string_0.length() - 3) + "crc" # crcFileContents = None # with open(crcFileDir, 'rb', 0) as tempFileCrc: # crcFileContents = tempFileCrc.read() # tempFileCrc.close() # if bytes != crcFileContents: # QMessageBox.warning(self, "Error", "Input file has been changed by outside.") # return DataHelper.loadInputParameters(filePathDir, self) return filePathDir except UserWarning as e: QMessageBox.warning(self, "Error", e.message) def exportResult(self): dlg = ExportDlg(self) dlg.ui.txtHeading.setText(self.surfaceType + "_Export") columnNames = [] if self.obstaclesModel != None: columnNames = self.obstaclesModel.fixedColumnLabels self.stModel = QStandardItemModel() for i in range(len(columnNames)): stItem = QStandardItem(columnNames[i]) stItem.setCheckable(True) checkFlag = True for hideColName in self.obstaclesModel.hideColumnLabels: if columnNames[i] == hideColName: checkFlag = False break if checkFlag: stItem.setCheckState(Qt.Checked) else: stItem.setCheckState(Qt.Unchecked) self.stModel.setItem(i, 0, stItem) if len(columnNames) <= 0: return dlg.ui.listColumns.setModel(self.stModel) result = dlg.exec_() return (result, dlg.resultHideColumnIndexs) def changeResultUnit(self): pass def method_27(self, qarecord_0): pass # QA.smethod_2(qarecord_0); # self.method_20(Messages.QA_UPDATED);
class GUI(QWidget): def __init__(self, parent=None): global f f = open(filename, "a") f.write("Widget init.\n") f.close() QWidget.__init__(self, parent, Qt.WindowStaysOnTopHint) self.__setup_gui__(self) self._flag = False self._change = False f = open(filename, "a") f.write("End of widget init.\n") f.close() def closeEvent(self, event): reply = QMessageBox.question(self, "Confirm", "Are you sure You want to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: event.accept() else: event.ignore() def __setup_gui__(self, Dialog): global f f = open(filename, "a") f.write("Setup of gui.\n") f.close() Dialog.setObjectName("Dialog") Dialog.resize(270, 145) self.setWindowTitle("Map Layer") screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) self.Render = QPushButton("Render", Dialog) self.Render.setGeometry(QRect(85, 90, 100, 25)) self.Render.setObjectName("Render") self.comboBox = QComboBox(Dialog) self.comboBox.setGeometry(QRect(100, 34, 115, 18)) self.comboBox.setEditable(False) self.comboBox.setMaxVisibleItems(11) self.comboBox.setInsertPolicy(QComboBox.InsertAtBottom) self.comboBox.setObjectName("comboBox") self.comboBox.addItems([ "Google Roadmap", "Google Terrain", "Google Satellite", "Google Hybrid", "Yahoo Roadmap", "Yahoo Satellite", "Yahoo Hybrid", "Bing Roadmap", "Bing Satellite", "Bing Hybrid", "Open Street Maps" ]) self.comboBox.setCurrentIndex(10) self.label1 = QLabel("Source:", Dialog) self.label1.setGeometry(QRect(55, 35, 35, 16)) self.label1.setObjectName("label1") self.slider = QSlider(Dialog) self.slider.setOrientation(Qt.Horizontal) self.slider.setMinimum(1) self.slider.setMaximum(12) self.slider.setValue(4) self.slider.setGeometry(QRect(110, 61, 114, 16)) self.label2 = QLabel("Quality: " + str(self.slider.value()), Dialog) self.label2.setGeometry(QRect(47, 61, 54, 16)) self.label2.setObjectName("label2") self.doubleSpinBox = QDoubleSpinBox(Dialog) self.doubleSpinBox.setGeometry(QRect(160, 5, 40, 20)) self.doubleSpinBox.setDecimals(0) self.doubleSpinBox.setObjectName("doubleSpinBox") self.doubleSpinBox.setMinimum(10.0) self.doubleSpinBox.setValue(20.0) self.doubleSpinBox.setEnabled(False) self.checkBox = QCheckBox("Auto refresh", Dialog) self.checkBox.setGeometry(QRect(50, 6, 100, 20)) self.checkBox.setLayoutDirection(Qt.RightToLeft) self.checkBox.setObjectName("checkBox") self.progressBar = QProgressBar(Dialog) self.progressBar.setGeometry(QRect(5, 130, 260, 10)) self.progressBar.setProperty("value", 0) self.progressBar.setTextVisible(False) self.progressBar.setObjectName("progressBar") self.progressBar.setVisible(False) QObject.connect(self.Render, SIGNAL("clicked()"), Dialog.__repaint__) QMetaObject.connectSlotsByName(Dialog) QObject.connect(self.slider, SIGNAL("valueChanged(int)"), self.__update_slider_label__) QObject.connect(self.comboBox, SIGNAL("activated(int)"), self.__combobox_changed__) self.timerRepaint = QTimer() QObject.connect(self.checkBox, SIGNAL("clicked()"), self.__activate_timer__) QObject.connect(self.timerRepaint, SIGNAL("timeout()"), self.__on_timer__) f = open(filename, "a") f.write("End of setup of gui.\n") f.close() def __combobox_changed__(self): self._change = True def __activate_timer__(self): self.doubleSpinBox.setEnabled(self.checkBox.isChecked()) if self.checkBox.isChecked(): self.timerRepaint.start(self.doubleSpinBox.value() * 1000) self.Render.setEnabled(False) if _progress == 0: self.__repaint__() else: self.timerRepaint.stop() self.Render.setEnabled(True) def __get_net_size__(self): global f f = open(filename, "a") f.write("Geting net size...\n") f.close() if not os.path.exists(Paths["Screenshot"]): Visum.Graphic.Screenshot(Paths["Screenshot"]) size = Image.open(Paths["Screenshot"]).size f = open(filename, "a") f.write("Read net size:" + str(size) + ".\n") f.close() return size def __on_timer__(self): global _paramGlobal self._flag = False Visum.Graphic.MaximizeNetWindow() param = _paramGlobal _paramGlobal = Visum.Graphic.GetWindow() shift = abs((param[0] - _paramGlobal[0]) / (param[2] - param[0])) zoom = abs((param[2] - param[0]) / (_paramGlobal[2] - _paramGlobal[0]) - 1) print _windowSizeGlobal if _windowSizeGlobal[2:4] != Visum.Graphic.GetMainWindowPos()[2:4]: self.__get_net_size__() self._flag = True elif shift > 0.4 or zoom > 0.2: self._flag = True if self._flag or self._change and _progress == 0: self.__repaint__() self._change = False def __update_slider_label__(self, value): self.label2.setText("Quality: " + str(value)) self._change = True def __update_progress_bar__(self): if _progress != 0: self.progressBar.setVisible(True) self.progressBar.setValue(_progress) else: self.progressBar.setVisible(False) def __rebuild_paths__(self): global Paths Paths["Images"] = [] list = os.listdir(Paths["ScriptFolder"]) imageList = [] for i in range(len(list)): if list[i][-3:] == "png": imageList.append(list[i]) for i in range(len(imageList)): try: Visum.Graphic.Backgrounds.ItemByKey(imageList[i]) Paths["Images"].append(Paths["ScriptFolder"] + "\\" + imageList[i]) except: pass def __repaint__(self): global _progress, f if len(Visum.Graphic.Backgrounds.GetAll) != len(Paths["Images"]): self.__rebuild_paths__() if _progress == 0: f = open(filename, "a") f.write("Doing repaint...\n") f.close() QWebSettings.clearMemoryCaches() timer = QTimer() timer.start(100) QObject.connect(timer, SIGNAL("timeout()"), self.__update_progress_bar__) Main(self.comboBox.currentIndex(), Visum.Graphic.GetWindow(), self.slider.value() / 4.0, self.__get_net_size__()) Visum.Graphic.Draw() self.__update_progress_bar__() _progress = 0 QTimer().singleShot(1500, self.__update_progress_bar__) f = open(filename, "a") f.write("End of doing repaint.\n") f.close()
class RemoveClassDialog(QDialog): pagetitle = 'Change Class' holdc = {} hold = [] def __init__(self, session, students, parent=None): super(RemoveClassDialog, self).__init__(parent) ko = 0 self.students = self.pullStudents(students) self.session = session[2] self.frame1 = QGroupBox('Remove From Class') hc1_box = QVBoxLayout() ses_name = str(session[1]) + ' ' + str(session[3] + ' Term') ses = QLabel(ses_name) hc1_box.addWidget(ses) self.li = [] self.liID = [] for student in self.students: num = student['id'] self.liID.append(num) self.c = QCheckBox('cb' + str(num)) self.c.setText( str(student['surname'] + ' ' + student['firstname'] + ' ' + student['othername']).title()) self.c.setObjectName("chk" + str(num)) self.c.setChecked(True) self.c.toggled.connect( lambda state, x=num, y=self.c: self.catItems(x, y)) hc1_box.addWidget(self.c) self.li.append(self.c) ko += 1 self.li1 = [] self.li1ID = [] self.frame1.setLayout(hc1_box) #frame1.setFrameShape(QFrame.StyledPanel) self.pb = QPushButton() self.pb.setObjectName("setclass") self.pb.setText("Set Class") self.pb2 = QPushButton() self.pb2.setObjectName("Cancel") self.pb2.setText("Cancel") but_box = QHBoxLayout() but_box.addWidget(self.pb2) but_box.addWidget(self.pb) main_box = QVBoxLayout() main_box.addWidget(self.frame1) main_box.addLayout(but_box) self.setLayout(main_box) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click()) self.connect(self.pb2, SIGNAL("clicked()"), lambda: self.button_close()) self.setWindowTitle(self.pagetitle) def catItems(self, a, b): _a = a self.cas = self.pullCas(_a) self.li1 = [] self.li1ID = [] for rp in self.hold: self.hc2_box.removeWidget(rp) sip.delete(rp) self.hold = [] ko = 0 for ca in self.cas: num = ca['id'] self.li1ID.append(num) self.c1 = QCheckBox('cbx' + str(num)) self.c1.setText(str(ca['name']).upper()) self.c1.setObjectName("chkx" + str(num)) self.c1.setChecked(True) self.hc2_box.addWidget(self.c1) self.hold.append(self.c1) self.li1.append(self.c1) ko += 1 #self.hc2_box.show() def pullClasz(self): cn = Db() arr = cn.selectn('datas', '', '', {'pubID': 11}) return arr def pullClass(self, a): self.a = a cn = Db() students = cn.select('datas', '', '', {'subID': self.a, 'active': 0}) arr = {} for j in students: arr[j[0]] = j[2] return arr def pullStudents(self, a): cn = Db() arr = cn.selectStudents(a) return arr def pullCas(self, a): _a = a cn = Db() arr = cn.selectn('datas', '', '', {'subID': _a}) return arr def button_close(self): self.reject() def button_click(self): students = self.getValue() session = self.session data = StudentTable() data.classRemoveStudent(session, students[0]) self.accept() def getValue(self): k1 = [] k2 = [] for s in range(0, len(self.li)): if self.li[s].isChecked(): k1.append(self.liID[s]) else: k2.append(self.liID[s]) k11 = [] k21 = [] for s in range(0, len(self.li1)): if self.li1[s].isChecked(): k11.append(self.li1ID[s]) else: k21.append(self.li1ID[s]) return [k1, k11] def pullSession(self, a): # select a file self.a = a g = Db() return g.select('session', '', 1, {'id': self.a})
def populateStatusBar(): statusBar = self.statusBar() w = QCheckBox("Render", self) w.setObjectName('renderCheck') w.setToolTip("Toggle map rendering") w.setChecked(True) statusBar.addPermanentWidget(w) w = QCheckBox("Marker", self) w.setObjectName('markerCheck') w.setToolTip("Toggle marker with cursor position from main map") w.setChecked(False) statusBar.addPermanentWidget(w, 1) w = QCheckBox("Extent", self) w.setObjectName('extentCheck') w.setToolTip("Show extent of main map") w.setChecked(False) statusBar.addPermanentWidget(w, 1) w = QToolButton(self) w.setObjectName('highlightBtn') w.setToolTip("Highlight extent in main map") w.setText("Highlight") statusBar.addPermanentWidget(w, 1) w = QLabel("Scale factor:", self) w.setObjectName('scaleFactorLabel') w.setAlignment(Qt.AlignRight | Qt.AlignVCenter) statusBar.addPermanentWidget(w, 1) w = QDoubleSpinBox(self) w.setObjectName('scaleFactorSpin') w.setToolTip("Current scale factor of main map") w.setMinimum(0.0) w.setMaximum(1000.0) w.setDecimals(3) w.setValue(1) w.setSingleStep(.05) statusBar.addPermanentWidget(w, 1) w = QToolButton(self) w.setObjectName('scaleBtn') w.setToolTip("Set scale for main map") w.setText("Scale: ") statusBar.addPermanentWidget(w, 1)
class SubjectForm(QDialog): pagetitle = 'Subject Manager' def __init__(self, parent=None): super(SubjectForm, self).__init__(parent) ko = 0 layout1 = QGridLayout() arr = self.pullClass() hold = {} for val in arr: self.num = val self.c = QCheckBox('cb' + str(val)) self.c.setText(str(arr[val][0]).upper()) self.c.setObjectName("chk" + str(val)) if (arr[val][3] == 0): self.c.setChecked(True) else: self.c.setChecked(False) self.c.toggled.connect( lambda state, x=val, y=self.c: self.chkFunc(x, y)) self.d = QLabel() self.d.setText(str(arr[val][1]).upper()) #self.b = QPushButton() #self.b.setObjectName("btn"+str(val)) #self.b.setText('Component') self.b1 = QPushButton() self.b1.setObjectName("btn1" + str(val)) self.b1.setText('Edit') #hold["btn"+str(val)] = self.b hold["btnx" + str(val)] = self.b1 layout1.addWidget(self.c, ko, 0) layout1.addWidget(self.d, ko, 1) #layout1.addWidget(self.b, ko, 2) layout1.addWidget(self.b1, ko, 3) ko += 1 for j in arr: self.h = j b1 = "btnx" + str(j) self.connect(hold[b1], SIGNAL("clicked()"), lambda gh=j: self.lunchEditForm(gh, self)) groupBox1 = QGroupBox('All Subjects') groupBox1.setLayout(layout1) self.pb = QPushButton() self.pb.setObjectName("Add") self.pb.setText("Add Subject") self.pb1 = QPushButton() self.pb1.setObjectName("Cancel") self.pb1.setText("Cancel") hbo = QHBoxLayout() hbo.addWidget(self.pb1) hbo.addStretch() hbo.addWidget(self.pb) groupBox2 = QGroupBox('') groupBox2.setLayout(hbo) grid = QGridLayout() grid.addWidget(groupBox1, 0, 0) grid.addWidget(groupBox2, 1, 0) self.setLayout(grid) self.connect(self.pb, SIGNAL("clicked()"), lambda: self.lunchAddForm(self)) self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_close()) self.setWindowTitle(self.pagetitle) def chkFunc(self, a, b): # shost is a QString object self.a = a self.b = b g = Db() if b.isChecked() == True: y = {'active': 0} else: y = {'active': 1} z = {'id': self.a} j = g.update('datas', y, z) return j def pullClass(self): cn = Db() dts = cn.selectn('datas', '', '', {'pubID': 3}) arr = {} try: for j in dts: arr[j['id']] = [j['name'], j['abbrv'], j['subID'], j['active']] except: pass return arr def lunchUnitForm(self, a, b): b.close() self.a = a self.form = CompForm(self.a) self.form.show() def lunchEditForm(self, a, b): b.close() self.a = a self.form = EditForm(self.a) self.form.show() def lunchAddForm(self, a): a.close() self.form = AddForm() self.form.show() def lunchForm(self): self.__init__() self.reloadSession() def button_close(self): self.close()
class Gui(object): def __init__(self, MainWindow): MainWindow.setObjectName("MainWindow") #Set size of window and make it non-resizeable MainWindow.resize(818, 665) MainWindow.setFixedHeight(665) MainWindow.setFixedWidth(818) MainWindow.setWindowTitle("Map Master: Search for the Lost City") MainWindow.setWindowIcon(QIcon("icon_medium.ico")) #Set window backgrounds self.background = QLabel(MainWindow) self.backgroundPixmapMenu = QPixmap(normpath("images/gameMenu2.png")) self.backgroundPixmapSettings = QPixmap(normpath( "images/gameMenuSettings2.png")) self.background.setPixmap(self.backgroundPixmapMenu) self.background.setGeometry(QtCore.QRect(0, 0, 818, 665)) self.popupPixmap = QPixmap(normpath("images/popupBG.png")) font = QFont() if "linux" in platform: font.setFamily("Century Schoolbook L") else: font.setFamily("Century Schoolbook") #Stylesheet settings for labels and buttons self.fg = "QLabel {color:black}" self.fgb = "QPushButton {color:black}" self.centralwidget = QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.setObjectName("gridLayout") self.stackedWidget = QStackedWidget(self.centralwidget) self.stackedWidget.setEnabled(True) self.stackedWidget.setObjectName("stackedWidget") #Main Menu page self.menuPage = QWidget() self.menuPage.setObjectName("menuPage") self.startButton = QPushButton(self.menuPage) self.startButton.setStyleSheet(self.fgb) self.startButton.setGeometry(QtCore.QRect(600, 200, 180, 60)) self.startButton.setText(QApplication.translate("MainWindow", "Start Game", None, QApplication.UnicodeUTF8)) self.startButton.setObjectName("startButton") font.setPointSize(15) self.startButton.setFont(font) self.loadButton = QPushButton(self.menuPage) self.loadButton.setStyleSheet(self.fgb) self.loadButton.setGeometry(QtCore.QRect(600, 280, 180, 60)) self.loadButton.setText(QApplication.translate("MainWindow", "Load Game", None, QApplication.UnicodeUTF8)) self.loadButton.setObjectName("loadButton") self.loadButton.setFont(font) self.settingsButton = QPushButton(self.menuPage) self.settingsButton.setStyleSheet(self.fgb) self.settingsButton.setGeometry(QtCore.QRect(600, 440, 180, 60)) self.settingsButton.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8)) self.settingsButton.setObjectName("settingsButton") self.settingsButton.setFont(font) self.quitButton = QPushButton(self.menuPage) self.quitButton.setStyleSheet(self.fgb) self.quitButton.setGeometry(QtCore.QRect(600, 520, 180, 60)) self.quitButton.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8)) self.quitButton.setObjectName("quitButton") self.quitButton.setFont(font) self.instrButton = QPushButton(self.menuPage) self.instrButton.setStyleSheet(self.fgb) self.instrButton.setGeometry(QtCore.QRect(600, 360, 180, 60)) self.instrButton.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8)) self.instrButton.setObjectName("instrButton") self.instrButton.setFont(font) self.stackedWidget.addWidget(self.menuPage) #Settings page self.settingsPage = QWidget() self.settingsPage.setObjectName("settingsPage") self.volumeSlider = QSlider(self.settingsPage) self.volumeSlider.setGeometry(QtCore.QRect(200, 200, 400, 30)) self.volumeSlider.setProperty("value", 50) self.volumeSlider.setOrientation(QtCore.Qt.Horizontal) self.volumeSlider.setObjectName("volumeSlider") self.soundLabel = QLabel(self.settingsPage) self.soundLabel.setGeometry(QtCore.QRect(340, 160, 120, 30)) font.setPointSize(20) self.soundLabel.setFont(font) self.soundLabel.setStyleSheet(self.fg) self.soundLabel.setText(QApplication.translate("MainWindow", "Volume", None, QApplication.UnicodeUTF8)) self.soundLabel.setAlignment(QtCore.Qt.AlignCenter) self.soundLabel.setObjectName("soundLabel") #Quiet Sound Graphic self.quietGraphic = QLabel(self.settingsPage) self.quietGraphic.setPixmap(QPixmap(normpath( "images/speakerQuiet.png"))) self.quietGraphic.setGeometry(QtCore.QRect(90, 180, 80, 80)) self.quietGraphic.setObjectName("quietGraphic") #Loud Sound Graphic self.loudGraphic = QLabel(self.settingsPage) self.loudGraphic.setPixmap(QPixmap(normpath("images/speakerLoud.png"))) self.loudGraphic.setEnabled(True) self.loudGraphic.setGeometry(QtCore.QRect(630, 180, 80, 80)) self.loudGraphic.setObjectName("loudGraphic") self.settingsLabel = QLabel(self.settingsPage) self.settingsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60)) font.setPointSize(36) self.settingsLabel.setFont(font) self.settingsLabel.setStyleSheet(self.fg) self.settingsLabel.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8)) self.settingsLabel.setAlignment(QtCore.Qt.AlignCenter) self.settingsLabel.setObjectName("settingsLabel") self.doneButton = QPushButton(self.settingsPage) self.doneButton.setStyleSheet(self.fgb) self.doneButton.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.doneButton.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8)) self.doneButton.setObjectName("doneButton") font.setPointSize(15) self.doneButton.setFont(font) self.stackedWidget.addWidget(self.settingsPage) self.soundManager = Sounds(self.volumeSlider.sliderPosition()) #Main Game page self.mainPage = QWidget() self.mainPage.setObjectName("mainPage") #Person View self.personView = ViewGraphics(self.mainPage) self.personView.setGeometry(QtCore.QRect(0, 0, 390, 500)) self.personView.setObjectName("personView") #Map View self.mapView = ViewGraphics(self.mainPage) self.mapView.setGeometry(QtCore.QRect(410, 0, 390, 500)) self.mapView.setObjectName("mapView") #ClueView self.clueView = QLabel(self.mainPage) self.clueView.setGeometry(QtCore.QRect(0, 510, 390, 91)) self.clueView.setObjectName("clueView") font.setPointSize(20) self.clueView.setFont(font) self.clueView.setStyleSheet(self.fg) #Map Toggles self.latLongCheck = QCheckBox(self.mainPage) self.latLongCheck.setGeometry(QtCore.QRect(420, 510, 103, 41)) self.latLongCheck.setText(QApplication.translate("MainWindow", "Latitude/ \n" "Longitude", None, QApplication.UnicodeUTF8)) self.latLongCheck.setObjectName("latLongCheck") font.setPointSize(12) self.latLongCheck.setFont(font) self.latLongCheck.setFocusPolicy(QtCore.Qt.NoFocus) self.colorCheck = QCheckBox(self.mainPage) self.colorCheck.setGeometry(QtCore.QRect(560, 510, 97, 41)) self.colorCheck.setText(QApplication.translate("MainWindow", "Color\n" "Coding", None, QApplication.UnicodeUTF8)) self.colorCheck.setObjectName("colorCheck") self.colorCheck.setFont(font) self.colorCheck.setFocusPolicy(QtCore.Qt.NoFocus) self.legendCheck = QCheckBox(self.mainPage) self.legendCheck.setGeometry(QtCore.QRect(680, 520, 97, 22)) self.legendCheck.setText(QApplication.translate("MainWindow", "Legend", None, QApplication.UnicodeUTF8)) self.legendCheck.setObjectName("legendCheck") self.legendCheck.setFocusPolicy(QtCore.Qt.NoFocus) font.setPointSize(12) self.legendCheck.setFont(font) self.searchButton = QPushButton(self.mainPage) self.searchButton.setStyleSheet(self.fgb) self.searchButton.setGeometry(QtCore.QRect(420, 560, 211, 55)) self.searchButton.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8)) self.searchButton.setObjectName("searchButton") font.setPointSize(15) self.searchButton.setFont(font) self.searchButton.setFocusPolicy(QtCore.Qt.NoFocus) #Score pieces self.scoreBox = QLabel(self.mainPage) self.scoreBox.setStyleSheet(self.fg) self.scoreBox.setGeometry(QtCore.QRect(720, 570, 71, 41)) self.scoreBox.setObjectName("scoreBox") self.scoreBox.setText(QApplication.translate("MainWindow", "0", None, QApplication.UnicodeUTF8)) self.scoreBox.setFont(font) self.scoreLabel = QLabel(self.mainPage) self.scoreLabel.setStyleSheet(self.fg) self.scoreLabel.setGeometry(QtCore.QRect(650, 580, 70, 17)) self.scoreLabel.setText(QApplication.translate("MainWindow", "Score:", None, QApplication.UnicodeUTF8)) self.scoreLabel.setAlignment(QtCore.Qt.AlignCenter) self.scoreLabel.setObjectName("scoreLabel") self.scoreLabel.setFont(font) self.popup = ViewGraphics(self.mainPage) self.popup.setStyleSheet( "QGraphicsView {background:transparent;border-style:none}") self.popupImage = self.popup.scene.addPixmap(self.popupPixmap) self.popup.setGeometry(QtCore.QRect(25, 25, 750, 450)) self.popup.setObjectName("popupLabel") font.setPointSize(25) self.popupText = self.popup.scene.addText("", font) self.textColor = QColor('black') self.popupText.setDefaultTextColor(self.textColor) self.popupText.setX(350) self.popupText.setY(225) self.popupImage.setOpacity(0) self.popupText.setOpacity(0) self.stackedWidget.addWidget(self.mainPage) #Help page self.helpPage = QWidget() self.helpPage.setObjectName("helpPage") self.HelpLabel = QLabel(self.helpPage) self.HelpLabel.setStyleSheet(self.fg) self.HelpLabel.setGeometry(QtCore.QRect(260, 30, 280, 60)) font.setPointSize(36) self.HelpLabel.setFont(font) self.HelpLabel.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8)) self.HelpLabel.setAlignment(QtCore.Qt.AlignCenter) self.HelpLabel.setObjectName("HelpLabel") self.wInstr = QLabel(self.helpPage) self.wInstr.setStyleSheet(self.fg) self.wInstr.setGeometry(QtCore.QRect(200, 150, 40, 30)) font.setPointSize(20) self.wInstr.setFont(font) self.wInstr.setText(QApplication.translate("MainWindow", "W", None, QApplication.UnicodeUTF8)) self.wInstr.setAlignment(QtCore.Qt.AlignCenter) self.wInstr.setObjectName("wInstr") self.sInstr = QLabel(self.helpPage) self.sInstr.setStyleSheet(self.fg) self.sInstr.setGeometry(QtCore.QRect(200, 200, 40, 30)) self.sInstr.setFont(font) self.sInstr.setText(QApplication.translate("MainWindow", "S", None, QApplication.UnicodeUTF8)) self.sInstr.setAlignment(QtCore.Qt.AlignCenter) self.sInstr.setObjectName("sInstr") self.aInstr = QLabel(self.helpPage) self.aInstr.setStyleSheet(self.fg) self.aInstr.setGeometry(QtCore.QRect(200, 250, 40, 30)) self.aInstr.setFont(font) self.aInstr.setText(QApplication.translate("MainWindow", "A", None, QApplication.UnicodeUTF8)) self.aInstr.setAlignment(QtCore.Qt.AlignCenter) self.aInstr.setObjectName("aInstr") self.dInstr = QLabel(self.helpPage) self.dInstr.setStyleSheet(self.fg) self.dInstr.setGeometry(QtCore.QRect(200, 300, 40, 30)) self.dInstr.setFont(font) self.dInstr.setText(QApplication.translate("MainWindow", "D", None, QApplication.UnicodeUTF8)) self.dInstr.setAlignment(QtCore.Qt.AlignCenter) self.dInstr.setObjectName("dInstr") self.wInstr2 = QLabel(self.helpPage) self.wInstr2.setStyleSheet(self.fg) self.wInstr2.setGeometry(QtCore.QRect(400, 150, 180, 30)) self.wInstr2.setFont(font) self.wInstr2.setText(QApplication.translate("MainWindow", "Move North", None, QApplication.UnicodeUTF8)) self.wInstr2.setAlignment(QtCore.Qt.AlignCenter) self.wInstr2.setObjectName("wInstr2") self.sInstr2 = QLabel(self.helpPage) self.sInstr2.setStyleSheet(self.fg) self.sInstr2.setGeometry(QtCore.QRect(400, 200, 180, 30)) self.sInstr2.setFont(font) self.sInstr2.setText(QApplication.translate("MainWindow", "Move South", None, QApplication.UnicodeUTF8)) self.sInstr2.setAlignment(QtCore.Qt.AlignCenter) self.sInstr2.setObjectName("sInstr2") self.aInstr2 = QLabel(self.helpPage) self.aInstr2.setStyleSheet(self.fg) self.aInstr2.setGeometry(QtCore.QRect(400, 250, 180, 30)) self.aInstr2.setFont(font) self.aInstr2.setText(QApplication.translate("MainWindow", "Move West", None, QApplication.UnicodeUTF8)) self.aInstr2.setAlignment(QtCore.Qt.AlignCenter) self.aInstr2.setObjectName("aInstr2") self.dInstr2 = QLabel(self.helpPage) self.dInstr2.setStyleSheet(self.fg) self.dInstr2.setGeometry(QtCore.QRect(400, 300, 180, 30)) self.dInstr2.setFont(font) self.dInstr2.setText(QApplication.translate("MainWindow", "Move East", None, QApplication.UnicodeUTF8)) self.dInstr2.setAlignment(QtCore.Qt.AlignCenter) self.dInstr2.setObjectName("dInstr2") self.searchInstr = QPushButton(self.helpPage) self.searchInstr.setStyleSheet(self.fgb) self.searchInstr.setEnabled(True) self.searchInstr.setGeometry(QtCore.QRect(170, 350, 100, 30)) self.searchInstr.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8)) self.searchInstr.setAutoDefault(False) self.searchInstr.setDefault(False) self.searchInstr.setFlat(False) self.searchInstr.setObjectName("searchInstr") font.setPointSize(15) self.searchInstr.setFont(font) self.dInstr2_2 = QLabel(self.helpPage) self.dInstr2_2.setStyleSheet(self.fg) self.dInstr2_2.setGeometry(QtCore.QRect(380, 350, 211, 30)) font.setPointSize(20) self.dInstr2_2.setFont(font) self.dInstr2_2.setText(QApplication.translate("MainWindow", "Search for clues", None, QApplication.UnicodeUTF8)) self.dInstr2_2.setAlignment(QtCore.Qt.AlignCenter) self.dInstr2_2.setObjectName("dInstr2_2") self.doneButton2 = QPushButton(self.helpPage) self.doneButton2.setStyleSheet(self.fgb) self.doneButton2.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.doneButton2.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8)) self.doneButton2.setObjectName("doneButton2") font.setPointSize(15) self.doneButton2.setFont(font) self.stackedWidget.addWidget(self.helpPage) #Credits page self.creditsPage = QWidget() self.creditsPage.setObjectName("creditsPage") self.creditsLabel = QLabel(self.creditsPage) self.creditsLabel.setStyleSheet(self.fg) self.creditsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60)) font.setPointSize(36) self.creditsLabel.setFont(font) self.creditsLabel.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8)) self.creditsLabel.setAlignment(QtCore.Qt.AlignCenter) self.creditsLabel.setObjectName("creditsLabel") self.credits = QLabel(self.creditsPage) self.credits.setStyleSheet(self.fg) self.credits.setGeometry(QtCore.QRect(180, 150, 500, 400)) font.setPointSize(20) self.credits.setFont(font) self.credits.setText(QApplication.translate("MainWindow", "Gary Lent\n" "Grant Stafford\n" "Jessie Liu\n" "Peter Andrien\n" "Nokia (Qt4 framework)\n" "Riverbank Computing Ltd (PyQt)\n" "Celestial Aeon Project", None, QApplication.UnicodeUTF8)) self.credits.setAlignment( QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.credits.setObjectName("credits") self.doneButton3 = QPushButton(self.creditsPage) self.doneButton3.setStyleSheet(self.fgb) self.doneButton3.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.doneButton3.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8)) self.doneButton3.setObjectName("doneButton3") font.setPointSize(15) self.doneButton3.setFont(font) self.stackedWidget.addWidget(self.creditsPage) #Story page self.storyPage = QWidget() self.storyPage.setObjectName("storyPage") self.storyLabel = QLabel(self.storyPage) self.storyLabel.setStyleSheet(self.fg) self.storyLabel.setGeometry(QtCore.QRect(100, 50, 600, 400)) font.setPointSize(25) self.storyLabel.setFont(font) self.storyLabel.setText(QApplication.translate("MainWindow", "My name is Travis Sinclair.\n I'm a skilled cartographer.\n I recently" " lost my job, but stumbled\n on a clue that may change my life" " \nforever. I've set off on a quest - a quest\n to find a lost city. " "I've found a clue,\n and believe there may be more.\n Help me find " "the lost city. ", None, QApplication.UnicodeUTF8)) self.storyLabel.setAlignment( QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.storyLabel.setObjectName("storyLabel") self.nextButton = QPushButton(self.storyPage) self.nextButton.setGeometry(QtCore.QRect(600, 520, 161, 61)) self.nextButton.setText(QApplication.translate("MainWindow", "Next", None, QApplication.UnicodeUTF8)) self.nextButton.setObjectName("nextButton") self.nextButton.setStyleSheet(self.fgb) font.setPointSize(15) self.nextButton.setFont(font) self.stackedWidget.addWidget(self.storyPage) self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) #Menu bar self.menubar = QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 818, 25)) self.menubar.setObjectName("menubar") self.menuMenu = QMenu(self.menubar) self.menuMenu.setTitle(QApplication.translate("MainWindow", "Menu", None, QApplication.UnicodeUTF8)) self.menuMenu.setObjectName("menuMenu") MainWindow.setMenuBar(self.menubar) self.actionSave_Game = QAction(MainWindow) self.actionSave_Game.setText(QApplication.translate("MainWindow", "Save Game", None, QApplication.UnicodeUTF8)) self.actionSave_Game.setObjectName("actionSave_Game") self.actionCredits = QAction(MainWindow) self.actionCredits.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8)) self.actionCredits.setObjectName("actionCredits") self.actionQuit = QAction(MainWindow) self.actionQuit.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8)) self.actionQuit.setObjectName("actionQuit") self.actionSettings = QAction(MainWindow) self.actionSettings.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8)) self.actionSettings.setObjectName("actionSettings") self.actionHelp = QAction(MainWindow) self.actionHelp.setText(QApplication.translate("MainWindow", "Help", None, QApplication.UnicodeUTF8)) self.actionHelp.setObjectName("actionHelp") self.actionMain_Menu = QAction(MainWindow) self.actionMain_Menu.setText(QApplication.translate("MainWindow", "Main Menu", None, QApplication.UnicodeUTF8)) self.actionMain_Menu.setObjectName("actionMain_Menu") self.menuMenu.addAction(self.actionSettings) self.menuMenu.addAction(self.actionHelp) self.menuMenu.addAction(self.actionSave_Game) self.menuMenu.addAction(self.actionCredits) self.menuMenu.addAction(self.actionMain_Menu) self.menuMenu.addAction(self.actionQuit) self.menubar.addAction(self.menuMenu.menuAction()) self.retranslateUi(MainWindow) self.stackedWidget.setCurrentIndex(0) self.stackIndex = 0 def retranslateUi(self, MainWindow): pass
class Dialog(toly_dialog.ToLyDialog): def __init__(self, parent=None): self.imp_prgm = "musicxml2ly" self.userg = "musicxml_import" self.noartCheck = QCheckBox() self.norestCheck = QCheckBox() self.nolayoutCheck = QCheckBox() self.nobeamCheck = QCheckBox() self.useAbsCheck = QCheckBox() self.commMidiCheck = QCheckBox() self.langCombo = QComboBox() self.langLabel = QLabel() self.impChecks = [self.noartCheck, self.norestCheck, self.nolayoutCheck, self.nobeamCheck, self.useAbsCheck, self.commMidiCheck] self.noartCheck.setObjectName("articulation-directions") self.norestCheck.setObjectName("rest-positions") self.nolayoutCheck.setObjectName("page-layout") self.nobeamCheck.setObjectName("import-beaming") self.useAbsCheck.setObjectName("absolute-mode") self.commMidiCheck.setObjectName("comment-out-midi") self.langCombo.addItem('') self.langCombo.addItems(_langlist) self.impExtra = [self.langLabel, self.langCombo] super(Dialog, self).__init__(parent) self.langCombo.currentIndexChanged.connect(self.makeCommandLine) app.translateUI(self) qutil.saveDialogSize(self, "musicxml_import/dialog/size", QSize(480, 260)) self.makeCommandLine() self.loadSettings() def translateUI(self): self.setWindowTitle(app.caption(_("Import Music XML"))) self.noartCheck.setText(_("Import articulation directions")) self.norestCheck.setText(_("Import rest positions")) self.nolayoutCheck.setText(_("Import page layout")) self.nobeamCheck.setText(_("Import beaming")) self.useAbsCheck.setText(_("Pitches in absolute mode")) self.commMidiCheck.setText(_("Comment out midi block")) self.langLabel.setText(_("Language for pitch names")) self.langCombo.setItemText(0, _("Default")) self.buttons.button(QDialogButtonBox.Ok).setText(_("Run musicxml2ly")) super(Dialog, self).translateUI() def makeCommandLine(self): """Reads the widgets and builds a command line.""" cmd = ["$musicxml2ly"] if self.useAbsCheck.isChecked(): cmd.append('-a') if not self.noartCheck.isChecked(): cmd.append('--nd') if not self.norestCheck.isChecked(): cmd.append('--nrp') if not self.nolayoutCheck.isChecked(): cmd.append('--npl') if not self.nobeamCheck.isChecked(): cmd.append('--no-beaming') if not self.commMidiCheck.isChecked(): cmd.append('-m') index = self.langCombo.currentIndex() if index > 0: cmd.append('--language=' + _langlist[index - 1]) cmd.append("$filename") self.commandLine.setText(' '.join(cmd)) def loadSettings(self): """Get users previous settings.""" self.imp_default = [False, False, False, False, False, False] self.settings = QSettings() self.settings.beginGroup('musicxml_import') super(Dialog, self).loadSettings() lang = self.settings.value("language", "default", type("")) try: index = _langlist.index(lang) except ValueError: index = -1 self.langCombo.setCurrentIndex(index + 1) def saveSettings(self): """Save users last settings.""" self.settings = QSettings() self.settings.beginGroup('musicxml_import') super(Dialog, self).saveSettings() index = self.langCombo.currentIndex() self.settings.setValue('language', 'default' if index == 0 else _langlist[index-1])
class CheckBox(QWidget): def __init__(self, parent): QWidget.__init__(self, parent) while not isinstance(parent, QDialog): parent = parent.parent() self.setObjectName("CheckBox" + str(len(parent.findChildren(CheckBox)))) self.hLayout = QHBoxLayout(self) self.hLayout.setObjectName("hLayout") self.hLayout.setSpacing(0) self.hLayout.setContentsMargins(0, 0, 0, 0) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth()) self.setSizePolicy(sizePolicy) self.checkBox = QCheckBox(self) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) self.checkBox.setObjectName(self.objectName() + "_checkbox") sizePolicy.setHeightForWidth( self.checkBox.sizePolicy().hasHeightForWidth()) self.checkBox.setSizePolicy(sizePolicy) self.hLayout.addWidget(self.checkBox) self.checkBox.setChecked(True) self.checkBox.clicked.connect(self.clicked) def clicked(self): self.emit(SIGNAL("Event_0"), self) def get_Caption(self): return self.checkBox.text() def set_Caption(self, captionStr): self.checkBox.setText(captionStr) Caption = property(get_Caption, set_Caption, None, None) def get_Enabled(self): return self.isEnabled() def set_Enabled(self, bool): self.setEnabled(bool) Enabled = property(get_Enabled, set_Enabled, None, None) def get_Visible(self): return self.isVisible() def set_Visible(self, bool): self.setVisible(bool) Visible = property(get_Visible, set_Visible, None, None) def get_Checked(self): return self.checkBox.isChecked() def set_Checked(self, bool): self.checkBox.setChecked(bool) Checked = property(get_Checked, set_Checked, None, None) def set_LabelWidth(self, width): self.checkBox.setMinimumSize(QSize(width, 0)) self.checkBox.setMaximumSize(QSize(width, 16777215)) LabelWidth = property(None, set_LabelWidth, None, None)
def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.configOptions, self.checkBoxList, self.configBool = {}, {}, None # Check for root privileges if geteuid() != 0: msg = ("{} is not root. You need to run with root priviliges\n" "Please use kdesudo, gksu or sudo/sux.").format(getuser()) QMessageBox.critical(self, __doc__ + "- Error", msg) sys.exit(1) else: msg = "This tool is running with root priviliges." QMessageBox.warning(self, __doc__ + "- Warning", msg) # title, icon and sizes self.setWindowTitle(__doc__) self.setMinimumSize(400, 400) self.setMaximumSize(2048, 2048) self.resize(600, 600) self.setWindowIcon(QIcon.fromTheme("preferences-system")) self.menuBar().addMenu("&File").addAction("Exit", exit) QShortcut("Ctrl+q", self, activated=lambda: self.close()) # main group main_group = QGroupBox("Module configuration") self.setCentralWidget(main_group) self.layout = QVBoxLayout(main_group) # scrollarea widgets self.scrollArea, self.window = QScrollArea(), QWidget() self.layout.addWidget(self.scrollArea) self.vbox = QVBoxLayout(self.window) # Graphic effect glow = QGraphicsDropShadowEffect(self) glow.setOffset(0) glow.setBlurRadius(99) glow.setColor(QColor(99, 255, 255)) self.scrollArea.setGraphicsEffect(glow) glow.setEnabled(True) # config loading stuff self.findConfig(CONFIG_DIR) for eachOption in tuple(self.configOptions.keys()): self.readConfig(eachOption, self.configOptions) self.subLayout = QHBoxLayout() self.checkBoxName = "checkBox_" + eachOption checkBoxList = QCheckBox(self.checkBoxName, self) self.checkBoxList[self.checkBoxName] = checkBoxList checkBoxList.setObjectName(self.checkBoxName) checkBoxList.setText("Enable module {}".format(eachOption)) if self.tooltip is not '': checkBoxList.setToolTip(self.tooltip) else: tooltip = "Configuration settings for {}".format(eachOption) checkBoxList.setToolTip(tooltip) if self.configBool: checkBoxList.setChecked(True) self.subLayout.addWidget(checkBoxList) self.vbox.addLayout(self.subLayout) self.scrollArea.setWidget(self.window) # Bottom Buttons Bar self.pushButtonSleep = QPushButton("Sleep") self.pushButtonSleep.setToolTip("Trigger Suspend to RAM aka Sleep") self.pushButtonSleep.clicked.connect(self.sleep) self.pushButtonHibernate = QPushButton("Hibernate") self.pushButtonHibernate.setToolTip( "Trigger Suspend to Disk Hibernate") self.pushButtonHibernate.clicked.connect(self.hibernate) self.buttonBox = QDialogButtonBox() self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Close | QDialogButtonBox.Help) self.buttonBox.addButton(self.pushButtonHibernate, QDialogButtonBox.ActionRole) self.buttonBox.addButton(self.pushButtonSleep, QDialogButtonBox.ActionRole) self.layout.addWidget(self.buttonBox) self.buttonBox.rejected.connect(exit) self.buttonBox.accepted.connect(self.writeConfig) self.buttonBox.helpRequested.connect(lambda: open_new_tab(WEBPAGE_URL))
def showPluginsSearchOptions(self): ''' Loads the search options of all the selected plugins and populates the relevant UI elements with input fields for the string options and checkboxes for the boolean options ''' pl = [] for pluginName in list(set([target['pluginName'] for target in self.ProjectWizardSelectedTargetsTable.targets])): plugin = self.PluginManager.getPluginByName(pluginName, 'Input') self.enabledPlugins.append(plugin) pl.append(plugin) ''' Build the configuration page from the available saerch options and add the page to the stackwidget ''' page = QWidget() page.setObjectName(_fromUtf8('searchconfig_page_' + plugin.name)) scroll = QScrollArea() scroll.setWidgetResizable(True) layout = QVBoxLayout() titleLabel = QLabel(_fromUtf8(plugin.name + self.trUtf8(' Search Options'))) layout.addWidget(titleLabel) vboxWidget = QWidget() vboxWidget.setObjectName(_fromUtf8('searchconfig_vboxwidget_container_' + plugin.name)) vbox = QGridLayout() vbox.setObjectName(_fromUtf8('searchconfig_vbox_container_' + plugin.name)) gridLayoutRowIndex = 0 ''' Load the String options first ''' pluginStringOptions = plugin.plugin_object.readConfiguration('search_string_options')[1] if pluginStringOptions: for idx, item in enumerate(pluginStringOptions.keys()): itemLabel = plugin.plugin_object.getLabelForKey(item) label = QLabel() label.setObjectName(_fromUtf8('searchconfig_string_label_' + item)) label.setText(itemLabel) vbox.addWidget(label, idx, 0) value = QLineEdit() value.setObjectName(_fromUtf8('searchconfig_string_value_' + item)) value.setText(pluginStringOptions[item]) vbox.addWidget(value, idx, 1) gridLayoutRowIndex = idx + 1 ''' Load the boolean options ''' pluginBooleanOptions = plugin.plugin_object.readConfiguration('search_boolean_options')[1] if pluginBooleanOptions: for idx, item in enumerate(pluginBooleanOptions.keys()): itemLabel = plugin.plugin_object.getLabelForKey(item) cb = QCheckBox(itemLabel) cb.setObjectName(_fromUtf8('searchconfig_boolean_label_' + item)) if pluginBooleanOptions[item] == 'True': cb.toggle() vbox.addWidget(cb, gridLayoutRowIndex + idx, 0) #If there are no search options just show a message if not pluginBooleanOptions and not pluginStringOptions: label = QLabel() label.setObjectName(_fromUtf8('no_search_config_options')) label.setText(self.trUtf8('This plugin does not offer any search options.')) vbox.addWidget(label,0,0) vboxWidget.setLayout(vbox) scroll.setWidget(vboxWidget) layout.addWidget(scroll) layout.addStretch(1) page.setLayout(layout) self.ui.searchConfiguration.addWidget(page) self.ui.searchConfiguration.setCurrentIndex(0) self.SearchConfigPluginConfigurationListModel = PluginConfigurationListModel(pl, self) self.SearchConfigPluginConfigurationListModel.checkPluginConfiguration() self.ui.personProjectWizardSearchConfigPluginsList.setModel(self.SearchConfigPluginConfigurationListModel) self.ui.personProjectWizardSearchConfigPluginsList.clicked.connect(self.changePluginConfigurationPage)
class Dialog(toly_dialog.ToLyDialog): def __init__(self, parent=None): self.imp_prgm = "abc2ly" self.userg = "abc_import" self.nobeamCheck = QCheckBox() self.impChecks = [self.nobeamCheck] self.nobeamCheck.setObjectName("import-beaming") self.impExtra = [] super(Dialog, self).__init__(parent) app.translateUI(self) qutil.saveDialogSize(self, "abc_import/dialog/size", QSize(480, 160)) self.makeCommandLine() self.loadSettings() def translateUI(self): self.nobeamCheck.setText(_("Import beaming")) self.buttons.button(QDialogButtonBox.Ok).setText(_("Run abc2ly")) super(Dialog, self).translateUI() def makeCommandLine(self): """Reads the widgets and builds a command line.""" cmd = ["$abc2ly"] if self.nobeamCheck.isChecked(): cmd.append('-b') cmd.append("$filename") self.commandLine.setText(' '.join(cmd)) def run_command(self): """ABC import (at least for now) needs a specific solution here.""" cmd = self.getCmd() directory = util.tempdir() proc = subprocess.Popen(cmd, cwd=directory, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE) stdouterr = proc.communicate() if not stdouterr[0]: with open(os.path.join(directory, cmd[-1])) as abc: stdouterr = (abc.read(), stdouterr[1]) return stdouterr def loadSettings(self): """Get users previous settings.""" self.imp_default = [True] self.settings = QSettings() self.settings.beginGroup('abc_import') super(Dialog, self).loadSettings() def saveSettings(self): """Save users last settings.""" self.settings = QSettings() self.settings.beginGroup('abc_import') super(Dialog, self).saveSettings()