def testButtonClickClose(self): button = QPushButton() button.connect(button, SIGNAL('clicked()'), SLOT('close()')) button.show() self.assert_(button.isVisible()) button.click() self.assert_(not button.isVisible())
def testSetFocusWidget(self): widget = QPushButton() widget.show() context = self.app.inputContext() self.assertEqual(context.focusWidget(), None) if not widget.testAttribute(Qt.WA_InputMethodEnabled): widget.setAttribute(Qt.WA_InputMethodEnabled) context.setFocusWidget(widget) self.assertEqual(context.focusWidget(), widget)
class AudioTest(QMainWindow): def __init__(self, filename): QMainWindow.__init__(self) self.playButton = QPushButton('Play!') self.source = QUrl.fromLocalFile(filename) self.player = QMediaPlayer() self.player.setMedia(self.source) self.playButton.clicked.connect(self.play) self.setCentralWidget(self.playButton) self.playButton.show() def play(self): self.player.play()
class DBusWidget(dbus.service.Object): def __init__(self, name, session): # export this object to dbus dbus.service.Object.__init__(self, name, session) # create a simple widget self.widget = QPushButton() self.widget.resize(200, 50) # To export a Qt signal as a DBus-signal, you need to connect it to a method in this class. # The method MUST have the signal annotation, so python-dbus will export it as a dbus-signal QObject.connect(self.widget, SIGNAL("clicked()"), self.clicked) QObject.connect(QApplication.instance(), SIGNAL("lastWindowClosed()"), self.lastWindowClosed) # You can export methods to dbus like you do in python-dbus. @dbus.service.method("com.example.SampleWidget", in_signature='', out_signature='') def show(self): self.widget.show() # Another method... now with a parameter @dbus.service.method("com.example.SampleWidget", in_signature='s', out_signature='') def setText(self, value): self.widget.setText(value) # Another one... @dbus.service.method("com.example.SampleWidget", in_signature='', out_signature='') def exit(self): qApp().quit() # A signal that will be exported to dbus @dbus.service.signal("com.example.SampleWidget", signature='') def clicked(self): pass # Another signal that will be exported to dbus @dbus.service.signal("com.example.SampleWidget", signature='') def lastWindowClosed(self): pass
from PySide.QtGui import QApplication, QPushButton #-------------------------------------- app = QApplication([]) #-------------------------------------- button = QPushButton('Exit') button.clicked.connect(app.exit) button.show() #-------------------------------------- app.exec_() #--------------------------------------
createButton = QPushButton("Create") createLayout.addWidget(createButton) createLayout.addStretch() layout.addStretch() doneButton = QPushButton("Done") doneButton.setParent(widget) createLayout.insertWidget(0, doneButton) doneButton.hide() createButton.hide() doneButton.show() doneButton.hide() createButton.show() nameToCreate = QLineEdit() nameToCreate.setParent(widget) createLayout.insertWidget(createLayout.count()-2, nameToCreate) doneButton.hide() nameToCreate.hide() def doCreate(): createButton.hide() doneButton.show() nameToCreate.show()
#coding:utf-8 # 导入必须模块 import sys from PySide.QtCore import Qt from PySide.QtGui import QApplication, QLabel, QPushButton def cmd_print_info(): print "cmd_print" # 主函数 if __name__ == '__main__': myApp = QApplication(sys.argv) # 创建Label并设置它的属性 button = QPushButton(u"按钮测试") button.clicked.connect(cmd_print_info) appLabel = QLabel() appLabel.setText(u"<font color=red size=40>这是我的第一个PySide程序</font>") appLabel.setAlignment(Qt.AlignCenter) appLabel.setWindowTitle(u"PySide测试程序") appLabel.setGeometry(300, 300, 600, 300) appLabel.show() # 显示这个Label button.show() # 运行main application myApp.exec_() sys.exit()
class EditorWindow(QMainWindow): """initialize editor""" def __init__(self, tixi, xmlFilename, cpacs_scheme=Config.path_cpacs_21_schema): super(EditorWindow, self).__init__() self.cur_file_path = "" self.cur_schema_path = "" self.setupEditor() self.setupButtonMenu() self.setupSearchBox() self.setupStatusbar() self.setupMenubar() self.setupNumbar() self.popUpWidget = None self.flag_layout = False self.hbox = QHBoxLayout() self.hbox.setSpacing(0) self.hbox.setContentsMargins(0,0,0,0) self.hbox.addWidget(self.number_bar) self.hbox.addWidget(self.editor) self.layout = QGridLayout() self.layout.addWidget(self.searchbox, 0, 0, 1, 4) self.layout.addWidget(self.button1, 0, 4, 1, 1) self.layout.addWidget(self.button2, 0, 5, 1, 1) self.layout.addLayout(self.hbox, 2, 0, 1, 8) self.layout.addWidget(self.fontsizeSpinBox, 0, 6, 1, 1) self.layout.addWidget(self.label1, 0, 7, 1, 1) self.window = QWidget() self.window.setLayout(self.layout) self.setWindowTitle('Simple XML editor') self.setCentralWidget(self.window) self.resize(800, 800) self.show() self.tixi = tixi self.loadFile(xmlFilename, cpacs_scheme) ''' loads cpacs file and validates it against the cpacs_schema @param xmlFilename: input file @param cpacs_scheme: validation scheme ''' def loadFile(self, xmlFilename=None, cpacs_scheme=Config.path_cpacs_21_schema): if xmlFilename and cpacs_scheme : try: self.tixi.open(xmlFilename) #self.tixi.openDocument(xmlFilename) #self.tixi.schemaValidateFromFile(cpacs_scheme) self.editor.setPlainText(self.tixi.exportDocumentAsString()) self.cur_file_path = xmlFilename self.cur_schema_path = cpacs_scheme except TixiException as e: self.statusBar().showMessage('CPACS ERROR: ' + e.error) ''' update the dictionary by the cpacs scheme @param path_dict: path to directory @param path_scheme: path to cpacs_scheme ''' def updatedictionary(self, path_dict=Config.path_code_completion_dict, path_scheme=Config.path_cpacs_21_schema): found = False olddict = open(path_dict) scheme_file = open(path_scheme, 'r') with open(path_dict, "a") as newdict : for line in scheme_file : word = re.search("(?<=\<xsd:complexType name=\").*(?=\"\>)", line) if word != None : for tmp in olddict : if tmp == word.group(0) +"\n" : found = True break if(not found) : newdict.write(word.group(0)+"\n") olddict.seek(0) found = False olddict.close() newdict.close() scheme_file.close() ''' validate xml file and write result to statusBar ''' def validate(self): try: etree.fromstring(str(self.editor.toPlainText())) self.statusBar().showMessage("Valid XML") except etree.XMLSyntaxError as e: if e.error_log.last_error is not None: msg = e.error_log.last_error.message line = e.error_log.last_error.line col = e.error_log.last_error.column self.statusBar().showMessage("Invalid XML: Line %s, Col %s: %s"%(line,col,msg)) except: self.statusBar().showMessage("Invalid XML: Unknown error") ''' close and cleanup tixi ''' def __del__(self): pass #self.tixi.close() #self.tixi.cleanup() ''' set and connect the search buttons ''' def setupButtonMenu(self): self.button1 = QPushButton("previous" ) self.button2 = QPushButton("next" ) self.label1 = QLabel("font") self.fontsizeSpinBox = QSpinBox() self.button1.hide() self.button2.hide() self.label1.hide() self.fontsizeSpinBox.hide() self.button1.clicked.connect(self.fire_search_backward) self.button2.clicked.connect(self.fire_search_foreward) self.fontsizeSpinBox.setRange(4, 30) self.fontsizeSpinBox.setSingleStep(1) self.fontsizeSpinBox.setSuffix('pt') self.fontsizeSpinBox.setValue(10) self.fontsizeSpinBox.valueChanged.connect(self.setfontsize) def setfontsize(self, value): self.font.setPointSize(value) self.editor.setFont(self.font) def setupEditor(self): self.font = QFont() self.font.setFamily('Courier') self.font.setFixedPitch(True) self.font.setPointSize(10) self.editor = EditorCodeCompletion(Config().path_code_completion_dict) self.editor.setFont(self.font) self.editor.setTabStopWidth(20) self.editor.setAcceptRichText(False) self.editor.setLineWrapMode(QTextEdit.NoWrap) self.editor.textChanged.connect(self.validate) self.highlighter = Highlighter(self.editor.document()) def setupNumbar(self): self.number_bar = NumberBar() self.number_bar.setTextEdit(self.getStates()) self.editor.cursorPositionChanged.connect(self.fireUpdateNumbar) self.connect(self.editor.verticalScrollBar(), SIGNAL("valueChanged(int)"), self.fireUpdateNumbar) #self.editor.verticalScrollBar.valueChanged.connect(self.fireUpdateNumbar) def setupStatusbar(self): self.lineNumber = -1 self.colNumber = -1 self.m_statusRight = QLabel("row: " + str(self.lineNumber) + ", col:" + str(self.colNumber), self) self.statusBar().addPermanentWidget(self.m_statusRight, 0) def setupSearchBox(self): self.searchbox = SearchField() self.searchbox.hide() def setupMenubar(self): commentAction = QAction('Comment', self) commentAction.setShortcut('Ctrl+K') commentAction.setStatusTip('Comment Block') commentAction.triggered.connect(self.fireComment) uncommentAction = QAction('Uncomment', self) uncommentAction.setShortcut('Ctrl+Shift+K') uncommentAction.setStatusTip('Comment Block') uncommentAction.triggered.connect(self.fireUnComment) searchAction = QAction('search', self) searchAction.setShortcut('Ctrl+F') searchAction.setStatusTip('search') searchAction.triggered.connect(self.fireSearchView) newAction = QAction('New', self) newAction.setShortcut('Ctrl+N') newAction.setStatusTip('creats empty cpacs-file') newAction.triggered.connect(self.fireNewAction) self.updateAction = QAction('Update', self) self.updateAction.setShortcut('Ctrl+U') self.updateAction.setStatusTip('Update CPACS') self.updateAction.triggered.connect(self.fireUpdate) revertAction = QAction('Revert', self) revertAction.setShortcut('Ctrl+R') revertAction.triggered.connect(self.fireRevert) clearAction = QAction('Clear', self) clearAction.setStatusTip('Clear Editor') clearAction.triggered.connect(self.editor.clear) numbarAction = QAction('Line Number', self) numbarAction.triggered.connect(self.fireSwitchLayout) self.xpathAction = QAction('Current XPath', self) self.xpathAction.triggered.connect(self.getCursorXPath) link_to_node_YesAction = QAction('yes', self) link_to_node_YesAction.triggered.connect(self.dummyFuction) link_to_node_NoAction = QAction('no', self) link_to_node_NoAction.triggered.connect(self.dummyFuction) toolXAction = QAction('Tool X',self) toolXAction.triggered.connect(self.fireToolX) menubar = self.menuBar() filemenu = menubar.addMenu("File") filemenu.addAction(newAction) filemenu.addAction(self.updateAction) filemenu.addAction(revertAction) sourcemenu = menubar.addMenu("Source") sourcemenu.addAction(commentAction) sourcemenu.addAction(uncommentAction) sourcemenu.addAction(searchAction) editormenu = menubar.addMenu("Editor") editormenu.addAction(clearAction) editormenu.addSeparator() editormenu.addAction(numbarAction) editormenu.addAction(self.xpathAction) editormenu_child1 = editormenu.addMenu('Link to node') editormenu_child1.addAction(link_to_node_YesAction) editormenu_child1.addAction(link_to_node_NoAction) toolmenu = menubar.addMenu("Tools") toolmenu.addAction(toolXAction) self.editor.setContextMenuPolicy(Qt.CustomContextMenu) self.editor.customContextMenuRequested.connect(self.showMenu) #self.editor.connect(self.editor, SIGNAL( "customContextMenuRequested(QPoint)" ), self.showMenu ) def showMenu( self, pos ): """ Show a context menu for the active layer in the legend """ menu = self.editor.createStandardContextMenu() menu.addAction(self.xpathAction) menu.exec_(QtCore.QPoint( self.mapToGlobal( pos ).x() + 5, self.mapToGlobal( pos ).y() )) def fireUpdateNumbar(self): self.updateLineNumber() self.number_bar.update() def dummyFuction(self): print ("not implemented yet") def getStates(self): self.stats = { "searchbox":self.searchbox, "editor":self.editor} return self.stats ''' find previous button ''' def fire_search_backward(self): self.editor.find(self.searchbox.text(), QTextDocument.FindBackward) self.searchbox.setFocus() ''' find next button ''' def fire_search_foreward(self): #print self.tixi.getNumberOfChilds('/cpacs/vehicles/aircraft/model[@uID="Aircraft1"]/wings/wing[@uID="Aircraft1_Wing1"]/transformation[@uID="Aircraft1_Wing1_Transf"]/scaling[@uID="Aircraft1_Wing1_Transf_Sca"]/z') searchList = list(filter(lambda a : a!='', self.searchbox.text().split('/'))) if len(searchList) == 1 : if self.editor.find(searchList[0]) : pass elif not self.editor.find(searchList[0], QTextDocument.FindBackward): QMessageBox.about(self, "error", "String %s not found" % (searchList[0])) else : self.editor.moveCursor(QTextCursor.Start) self.editor.find(searchList[0]) else : self.searchXPath(self.searchbox.text(), searchList) self.searchbox.setFocus() # test # /cpacs/vehicles/aircraft/model/wings/wing/sections/section def searchXPath(self, path, searchList): try: if self.tixi.xPathEvaluateNodeNumber(path) > 1 : QMessageBox.about(self, "error", "XPath %s not unique" % path) return self.editor.moveCursor(QTextCursor.Start) found = True # search index snd loop j = 0 # search backwards for uid for i in range(len(searchList)-1, -1, -1) : if '[' in searchList[i] : # get value in brackets : [x] --> x uid = re.search(r'\[(.*)\]', searchList[i]).group(1) uid = self.__transToSearchUid(searchList[:i+1], uid) found = self.editor.find(uid) j = i+1 break # search forward for all nodes after last uid while found and j < len(searchList) : found = self.editor.find('<'+searchList[j]) j += 1 if not found : QMessageBox.about(self, "error", "XPath %s not found" % path) except TixiException : QMessageBox.about(self, "error", "XPath %s not found" % path) def __transToSearchUid(self, path_list, uid): try: int(uid) path = "" for p in path_list : path = path + '/' + p return self.tixi.getTextAttribute(path , 'uID') except ValueError: return uid.replace('@', '') def getCursorXPath(self): start_pos = self.editor.textCursor().position() tag , tag_pos , isCursorInTag = self.getTagNameAtCursor() _,xpath_idx, xpath_uid = self.__findXPath_rec('/cpacs', '/cpacs' , tag, tag_pos) if not isCursorInTag: xpath_idx = self.__strRemoveReverseToChar(xpath_idx, '/') xpath_uid = self.__strRemoveReverseToChar(xpath_uid, '/') self.__setCursorToPostion(start_pos) self.__startXPathPopUp(xpath_idx, xpath_uid) def getTagNameAtCursor(self): ''' @return: name of tag , position of tag , cursor is btw open and closing tag ''' self.editor.find('<', QTextDocument.FindBackward) isClosingTag , fst_tag = self.__getTagName() pos = self.editor.textCursor().position() if isClosingTag : # find open tag of this closing tag self.editor.find('<'+fst_tag, QTextDocument.FindBackward) pos = self.editor.textCursor().position() return fst_tag , pos , False else: return fst_tag , pos , True def __getTagName(self): tc = self.editor.textCursor() tc.select(QTextCursor.WordUnderCursor) tx = tc.selectedText() isClosingTag = False if "</" in tx : # select next word tc.select(QTextCursor.WordUnderCursor) tx = tc.selectedText() isClosingTag = True return isClosingTag , "" if "<" in tx else tx def __findXPath_rec(self, xpath_idx, xpath_uid, search, pos): nodes = self.__getChildNodesIdxTuple(xpath_idx) for (node, idx) in nodes: if node != '#text' : new_xpath_idx, new_xpath_uid = self.__createNewXPath(xpath_idx, xpath_uid, node, idx) if search == node and self.isNodeAtSearchedTagPosition(new_xpath_uid, pos) : print ("gefunden" , new_xpath_idx) return True, new_xpath_idx , new_xpath_uid else: flag , res_idx, res_uid = self.__findXPath_rec(new_xpath_idx, new_xpath_uid, search, pos) if flag : return True, res_idx, res_uid return False , xpath_idx , xpath_uid def __getChildNodesIdxTuple(self, xpath): n = self.tixi.getNumberOfChilds(xpath) + 1 node_list = list(map(lambda i : self.tixi.getChildNodeName(xpath, i), range(1,n))) res = [] for j in range(len(node_list)) : cnt = 1 for k in range(j): if node_list[k] == node_list[j] : cnt = cnt + 1 res.append((node_list[j],cnt)) return res def __createNewXPath(self, xpath_idx, xpath_uid, node, idx): path_idx = xpath_idx + '/' + node path_uid = xpath_uid + '/' + node try : uID = self.tixi.getTextAttribute(path_idx + '[' + str(idx) + ']', 'uID') path_idx = path_idx + '[' + str(idx) + ']' path_uid = path_uid+'[@uID="' + uID + '"]' except TixiException: pass # e.error == 'ATTRIBUTE_NOT_FOUND return path_idx , path_uid def isNodeAtSearchedTagPosition(self, xpath, pos): ''' @param xpath: xpath with uids (doesn't work with indices) @param param: ''' self.editor.moveCursor(QTextCursor.Start) # split string at / and remove all empty strings l = list(filter(lambda x : x != '' , xpath.split('/'))) # search index snd loop j = 0 # search backwards for uid for i in range(len(l)-1, -1, -1) : if '[' in l[i] : # get value in brackets : [x] --> x uid = re.search(r'\[@(.*)\]', l[i]).group(1) self.editor.find(uid) j = i+1 break # search forward for all nodes after last uid while j < len(l) : self.editor.find('<'+l[j]) j += 1 return pos <= self.editor.textCursor().position() def __setCursorToPostion(self, pos): tc = self.editor.textCursor() tc.setPosition(pos) self.editor.setTextCursor(tc) def __startXPathPopUp(self, xpath_idx, xpath_uid): self.popUpWidget = XPathDialog(xpath_idx, xpath_uid) self.setEnabled(False) self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def updateLineNumber(self): ''' sets the line and column number ''' self.lineNumber = self.editor.textCursor().blockNumber() + 1 self.colNumber = self.editor.textCursor().columnNumber() + 1 self.m_statusRight.setText("row: " + str(self.lineNumber) + ", col:" + str(self.colNumber)) def highlightCurrentLine(self) : ''' highlight line under cursor ''' extraSelections = [] selection = QTextEdit.ExtraSelection() lineColor = QColor(255, 250, 205) selection.format.setBackground(lineColor) selection.format.setProperty(QTextFormat.FullWidthSelection, True) selection.cursor = self.editor.textCursor() selection.cursor.clearSelection() extraSelections.append(selection) self.editor.setExtraSelections(extraSelections) self.editor.setFocus() #TODO: implemnt def fireUpdate(self): print ('dummy function - update the model') text_file = open(Config.path_cpacs_tmp_file, "w") text_file.write(self.editor.toPlainText()) text_file.close() #self.tixi.saveDocument(Config.path_cpacs_tmp_file) # '../cpacs_files/temp.xml' def fireRevert(self): ''' reloads cpacs file if not updated yet ''' if(self.cur_file_path and self.cur_schema_path) : self.loadFile(self.cur_file_path, self.cur_schema_path) else : QMessageBox.about(self, "error", "CPACS-File or Validation-Schema not available") def fireSwitchLayout(self): ''' function to show or hide line numbers ''' if(self.flag_layout) : self.number_bar.flag_show_numbers = True self.update() else : self.number_bar.flag_show_numbers = False self.update() self.flag_layout = not self.flag_layout def fireNewAction(self): ''' opens new file input form ''' self.setEnabled(False) self.popUpWidget = NewFileDialog() self.popUpWidget.buttonBox.accepted.connect(self.__createNewCpacsFile) self.popUpWidget.buttonBox.rejected.connect(self.__resetPopUpWidget) self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def fireToolX(self): self.popUpWidget = ToolX("X-Tool", self.tixi) self.setEnabled(False) self.popUpWidget.buttonBox.accepted.connect(self.__resetPopUpWidget) self.popUpWidget.buttonBox.rejected.connect(self.__resetPopUpWidget) # closeAct for pressing X to close window self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def __createNewCpacsFile(self): ''' closes all documents and creates new empty cpacs temporary file ''' idict = self.popUpWidget.fire_submitInput() self.tixi.closeAllDocuments() self.tixi.create('cpacs') self.tixi.addCpacsHeader(idict['name'], idict['creator'], idict['version'], idict['description'], idict['cpacsVersion']) self.tixi.saveDocument(Config.path_cpacs_tmp_file) self.loadFile(Config.path_cpacs_tmp_file) self.__resetPopUpWidget() def __resetPopUpWidget(self): self.popUpWidget.close() self.popUpWidget = None self.setEnabled(True) def fireComment(self): ''' inserts open respective closing tag before and after a selected text. ''' tc = self.editor.textCursor() tc.beginEditBlock() tc.setPosition(self.editor.textCursor().selectionStart()) tc.insertText("<!--") tc.setPosition(self.editor.textCursor().selectionEnd()) tc.insertText("-->") tc.endEditBlock() def fireUnComment(self): ''' removes open respective closing tag before and after a selected text. ''' tc = self.editor.textCursor() selectTxt = tc.selectedText() if selectTxt.find('<!--') != -1 : if selectTxt.rfind('-->') != -1 : selectTxt = selectTxt.replace('<!--', '', 1) selectTxt = self.__rreplace(selectTxt, '-->' , '', 1) tc.insertText(selectTxt) else: QMessageBox.about(self, "error", "no open tag (%s) in selection" % ('-->')) else: QMessageBox.about(self, "error", "no close tag (%s) in selection" % ('<!--')) def fireSearchView(self): ''' show and hide searchbox and buttons ''' if self.searchbox.isFocused() : self.searchbox.hide() self.button1.hide() self.button2.hide() self.label1.hide() self.fontsizeSpinBox.hide() else : self.searchbox.show() self.button1.show() self.button2.show() self.label1.show() self.fontsizeSpinBox.show() self.searchbox.setFocus() def keyPressEvent(self,event): ''' handle for searching strings by pressing enter key ''' if self.searchbox.isFocused() and event.key() == Qt.Key_Return : self.fire_search_foreward() # ====================================================================================================================== # utilities # ====================================================================================================================== def __strRemoveReverseToChar(self, s, c): return self.__rm_rec(s, c) def __rm_rec(self, s, c): if s == "" : return "" elif s[-1] == c : return s[:-1] else : return self.__rm_rec(s[:-1], c) def __rreplace(self, s, old, new, occurrence): ''' reverse string replace function @param s: source string @param old: char to be replaced @param new: new char @param occurrence: only the given count occurrences are replaced. ''' li = s.rsplit(old, occurrence) return new.join(li)
class ProfileSelection(QDialog): ''' classdocs ''' removeProfile = Signal(Athlete_Model) profileSelected = Signal(Athlete_Model) profileUpdate_request = Signal(Athlete_Model, Athlete_Model) lastProfileDeleted = Signal() def __init__(self, athletesList): ''' Constructor ''' QDialog.__init__(self) self.setWindowTitle("Profile Selection") self.athletesList = athletesList self._initGUI() def _initGUI(self): topHLayout = QHBoxLayout() hLayout = QHBoxLayout() vLayout = QVBoxLayout() # Label greeterText = QLabel("Welcome to <b>Pushup app</b>." + \ "<br><br> Select a profile:") vLayout.addWidget(greeterText) # List self.list = QListWidget() self.list.setMinimumWidth(150) self.list.setSelectionMode(QAbstractItemView.SingleSelection) # SingleSelection is the default value, but I prefer to be sure self.list.itemSelectionChanged.connect(self._activateButtons) for athlete in self.athletesList: iconW = QIcon.fromTheme("user-available") # doens't work on Mac and Windows # http://qt-project.org/doc/qt-4.8/qicon.html#fromTheme listW = QListWidgetItem(iconW, athlete._name) listW.setData(Qt.UserRole, athlete) self.list.addItem(listW) topHLayout.addWidget(self.list) self.profileWidget = ProfileFormWidget() self.profileWidget.hide() topHLayout.addWidget(self.profileWidget) vLayout.addLayout(topHLayout) vLayout.addLayout(hLayout) # Buttons self.okBtn = QPushButton("Ok") self.okBtn.setDisabled(True) self.okBtn.setDefault(True) self.okBtn.clicked.connect(self._okButtonSlot) self.list.itemDoubleClicked.connect(self._okButtonSlot) cancelBtn = QPushButton("Cancel") cancelBtn.clicked.connect(self._cancelButtonSlot) self.editBtn = QPushButton("Edit") self.editBtn.setDisabled(True) self.editBtn.setCheckable(True) self.editBtn.clicked.connect(self._toggleProfileEdit) self.saveBtn = QPushButton("Save changes") # Saves the changes made on the profile self.saveBtn.hide() self.saveBtn.clicked.connect(self._saveButtonSlot) self.removeProfileBtn = QPushButton("Remove Profile") self.removeProfileBtn.setDisabled(True) self.removeProfileBtn.clicked.connect(self._removeProfile_Dialog) hLayout.addWidget(self.editBtn) hLayout.addWidget(self.removeProfileBtn) hLayout.addWidget(cancelBtn) hLayout.addWidget(self.okBtn) hLayout.addWidget(self.saveBtn) self.setLayout(vLayout) def getSelectedProfile(self): selectedListItem = self.list.selectedItems()[0] athleteProfile = selectedListItem.data(Qt.UserRole) return athleteProfile def updateList(self, athletes): self.list.clear() self.athletesList = athletes for athlete in self.athletesList: iconW = QIcon.fromTheme("user-available") # doens't work on Mac and Windows # http://qt-project.org/doc/qt-4.8/qicon.html#fromTheme listW = QListWidgetItem(iconW, athlete._name) listW.setData(Qt.UserRole, athlete) self.list.addItem(listW) def resetWidget(self): """ Resets the widget to the initial laoyout. Should be used only in specific cases """ self.editBtn.setChecked(False) self._toggleProfileEdit() def _removeProfile_Dialog(self): """Runs a prompt dialog. Ask the user if he really wants to remove the selected profile. """ confirmationDialog = QMessageBox() confirmationDialog.setText("Do you really want to remove the selected profile ?") confirmationDialog.setInformativeText("Profile deletion can not be undone") confirmationDialog.setIcon(QMessageBox.Question) confirmationDialog.setStandardButtons(QMessageBox.Yes | QMessageBox.No) confirmationDialog.accepted.connect(self._emitRemoveProfile) ret = confirmationDialog.exec_() if ret==QMessageBox.Yes: self._emitRemoveProfile() def _emitRemoveProfile(self): athlete = self.getSelectedProfile() rowToDelete = 0 for index, element in enumerate(self.athletesList): if element == athlete: rowToDelete = index self.list.takeItem(rowToDelete) self.athletesList.remove(athlete) self.removeProfile.emit(athlete) def _okButtonSlot(self): athlete = self.list.selectedItems()[0].data(Qt.UserRole) self.accept() # is it correct ? Maybe self.close() is better ? # Or should I redefine the accept() method ? #athleteProfile = self.getSelectedProfile() self.profileSelected.emit(athlete) def _cancelButtonSlot(self): if len(self.athletesList) == 0: self.lastProfileDeleted.emit() self.reject() def _saveButtonSlot(self): selectedProfile = self.getSelectedProfile() updatedProfile = self.profileWidget.getProfile() self.profileUpdate_request.emit(selectedProfile, updatedProfile) #self._toggleProfileEdit() def _toggleProfileEdit(self): if self.editBtn.isChecked(): self.profileWidget.setProfile(self.getSelectedProfile()) self.profileWidget.show() self.saveBtn.show() self.okBtn.hide() self.removeProfileBtn.hide() else: self.saveBtn.hide() self.profileWidget.hide() self.okBtn.show() self.removeProfileBtn.show() def _activateButtons(self): selectedItems = self.list.selectedItems() if len(selectedItems)!=0 : self.okBtn.setDisabled(False) self.removeProfileBtn.setDisabled(False) self.editBtn.setDisabled(False) else : self.okBtn.setDisabled(True) self.removeProfileBtn.setDisabled(True) self.editBtn.setDisabled(True)
class PythonKeyboard(MAbstractInputMethod): EXAMPLE_SUBVIEW_ID = "ExamplePluginSubview1" def __init__(self, host, mainWindow): MAbstractInputMethod.__init__(self, host, mainWindow) self._showIsInhibited = False self._showRequested = False self._mainWidget = QPushButton("Hello World by PySide", mainWindow) self._mainWidget.clicked[None].connect(self.onButtonClicked) host.sendCommitString("Maliit") host.sendPreeditString("Mali", [], 0, 6) def onButtonClicked(self): self.inputMethodHost().sendCommitString(self._mainWidget.text()) def show(self): self._showRequested = True if self._showIsInhibited: return screenSize = qApp.desktop().screenGeometry().size() self._mainWidget.parentWidget().resize(screenSize) imGeometry = QRect(0, screenSize.height() - 200, screenSize.width(), 200); self._mainWidget.setGeometry(imGeometry) self.inputMethodHost().setScreenRegion(QRegion(self._mainWidget.geometry())) self.inputMethodHost().setInputMethodArea(QRegion(self._mainWidget.geometry())) self._mainWidget.show() def hide(self): if not self._showRequested: return; self._showRequested = False self._mainWidget.hide() self.inputMethodHost().setScreenRegion(QRegion()) self.inputMethodHost().setInputMethodArea(QRegion()) def subViews(self, state): subViews = [] if state == MInputMethod.OnScreen: subView1 = MAbstractInputMethod.MInputMethodSubView() subView1.subViewId = PythonKeyboard.EXAMPLE_SUBVIEW_ID subView1.subViewTitle = "Example plugin subview 1"; subViews.append(subView1) return subViews def activeSubView(self, state): if state == MInputMethod.OnScreen: return PythonKeyboard.EXAMPLE_SUBVIEW_ID else: return "" def setState(self, states): if MInputMethod.OnScreen in states: if self._showRequested and not self._showIsInhibited: self._mainWidget.show() else: self.mainWidget.hide() def handleClientChange(self): if self._showRequested: self.hide() def handleVisualizationPriorityChange(self, inhibitShow): if self._showIsInhibited == inhibitShow: return self._showIsInhibited = inhibitShow if self._showRequested: if inhibitShow: self._mainWidget.hide() else: self._mainWidget.show()
class Note(QtGui.QWidget): def __init__(self, message, mainGui, parent=None): super(Note, self).__init__(parent) self.mainGui = mainGui self.NOTE_WIDTH = 240 self.NOTE_HEIGHT = 240 self.setFixedSize(self.NOTE_WIDTH, self.NOTE_HEIGHT) self.setObjectName("note") self.drag = False # czy karteczka jest w trakcie przenoszenia? self.dragPos = QPoint() # pozycja rozpoczecia przenoszenia assert message self.setWindowFlags(Qt.FramelessWindowHint) self.setWindowTitle("Note") # FIXME # -- główne layouty -- self.globalVLayout = QtGui.QVBoxLayout(self) self.globalVLayout.setObjectName("globalVLayout") self.upperHLayout = QtGui.QHBoxLayout() self.upperHLayout.setObjectName("upperHLayout") self.globalVLayout.addLayout(self.upperHLayout) self.fromToForm = QtGui.QFormLayout() self.upperHLayout.addLayout(self.fromToForm) # -- layout z nadawcą i adresatami -- self.fromToForm.setSizeConstraint(QtGui.QLayout.SetFixedSize) self.fromToForm.setFieldGrowthPolicy(QtGui.QFormLayout.ExpandingFieldsGrow) self.fromToForm.setObjectName("fromToForm") self.fromLabel = QtGui.QLabel("From:", self) self.fromLabel.setObjectName("fromLabel") self.fromToForm.setWidget(0, QtGui.QFormLayout.LabelRole, self.fromLabel) self.fromToFormUpRight = QtGui.QHBoxLayout() self.fromToForm.setLayout(0, QtGui.QFormLayout.FieldRole, self.fromToFormUpRight) self.toLabel = QtGui.QLabel("To:", self) self.toLabel.setObjectName("toLabel") self.fromToForm.setWidget(1, QtGui.QFormLayout.LabelRole, self.toLabel) self.fromToFormDownRight = QtGui.QHBoxLayout() self.fromToForm.setLayout(1, QtGui.QFormLayout.FieldRole, self.fromToFormDownRight) # -- przyciski funkcyjne -- iconButtonPolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) iconButtonPolicy.setHorizontalStretch(0) iconButtonPolicy.setVerticalStretch(0) # -- przycisk wysłania -- self.sendButton = QPushButton(u"&Send") self.sendButton.setObjectName("sendButton") self.sendButton.setIcon(pea_app().send_icon) sendSizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) self.sendButton.setSizePolicy(sendSizePolicy) # -- przycisk dodawania self.addButton = QtGui.QPushButton(self) self.addButton.setObjectName("addButton") self.addButton.setSizePolicy(iconButtonPolicy) self.addButton.setIcon(pea_app().add_icon) self.sendButton.clicked.connect(self.sendMessage) # -- przycisk do dat self.datesButton = QtGui.QPushButton(self) self.datesButton.setCheckable(True) self.datesButton.setObjectName("datesButton") self.datesButton.setSizePolicy(iconButtonPolicy) self.datesButton.setIcon(pea_app().calendar_icon) # -- przycisk zamykania self.closeButton = QtGui.QPushButton(self) self.closeButton.setObjectName("closeButton") self.closeButton.setSizePolicy(iconButtonPolicy) self.closeButton.setIcon(pea_app().close_icon) # --- górny prawy --- self.senderUserEntry = QtGui.QLabel('') self.senderUserEntry.setObjectName("senderUserEntry") self.fromToFormUpRight.addWidget(self.senderUserEntry) self.fromToFormUpRight.addStretch() self.fromToFormUpRight.addWidget(self.sendButton) self.fromToFormUpRight.addWidget(self.datesButton) self.fromToFormUpRight.addWidget(self.closeButton) # --- # --- dolny prawy --- self.recipientsBox = QtGui.QLabel() self.fromToFormDownRight.addWidget(self.recipientsBox) self.fromToFormDownRight.addStretch() self.fromToFormDownRight.addWidget(self.addButton) # --- # -- linia oddzielająca nagłówek od treści self.line = QtGui.QFrame(self) self.line.setFrameShape(QtGui.QFrame.HLine) self.line.setFrameShadow(QtGui.QFrame.Sunken) self.line.setObjectName("line") self.globalVLayout.addWidget(self.line) # -- DATES -- # TODO: zmniejszyć czcionkę? self.datesForm = QtGui.QFormLayout() self.datesForm.setObjectName("datesForm") self.dateLabel = QtGui.QLabel("Date:", self) self.dateLabel.setObjectName("dateLabel") self.datesForm.setWidget(0, QtGui.QFormLayout.LabelRole, self.dateLabel) self.validLabel = QtGui.QLabel("Valid till:", self) self.validLabel.setObjectName("validLabel") self.datesForm.setWidget(1, QtGui.QFormLayout.LabelRole, self.validLabel) self.dateData = QtGui.QLabel(self) self.dateData.setObjectName("dateData") self.datesForm.setWidget(0, QtGui.QFormLayout.FieldRole, self.dateData) self.validData = QtGui.QLabel(self) self.validData.setObjectName("validData") self.datesForm.setWidget(1, QtGui.QFormLayout.FieldRole, self.validData) self.datesWidget = QtGui.QWidget() self.datesWidget.setLayout(self.datesForm) self.globalVLayout.addWidget(self.datesWidget) # -- obsługa chowania dat self.datesWidget.hide() self.datesButton.toggled.connect(self.toggleDatesWidget) # TODO: # -- obsługa dodawania adresata self.addButton.clicked.connect(self.selectRecipients) # -- pole treści self.noteContent = QtGui.QTextBrowser(self) self.noteContent.setEnabled(True) self.noteContent.setFrameShape(QtGui.QFrame.NoFrame) self.noteContent.setFrameShadow(QtGui.QFrame.Plain) self.noteContent.setReadOnly(True) self.noteContent.setObjectName("noteContent") self.globalVLayout.addWidget(self.noteContent) # -- obsługa zamykania self.closeButton.setShortcut(QtGui.QApplication.translate("note", "Ctrl+Q", None, QtGui.QApplication.UnicodeUTF8)) self.closeButton.clicked.connect(self.closeNote) # -- przyszłe okno wyboru adresatów self.selectRecipentsWindow = None # -- ustawienie treści self.setMessage(message) def setRecipients(self, recipients): '''Ustawia listę nadawców Argument recipients: lista str [odbiorca1, odbiorca2, ...]''' self.recipients_ = recipients rec_join = ', '.join(recipients) self.recipientsBox.setText(trunc_str(rec_join, 21)) self.recipientsBox.setToolTip(rec_join) def setSender(self, sender): '''Ustawia wysyłającego Argument sender: str nadawca''' self.sender_ = sender def mousePressEvent(self, event): self.raise_() if event.button() == Qt.LeftButton: self.drag = True self.dragPos = event.globalPos() - self.pos() def mouseReleaseEvent(self, event): self.drag = False def mouseMoveEvent(self, event): if self.drag: self.move(event.globalPos() - self.dragPos) def updateMessageState(self): s = self.__message__.state send_button = False if s == MsgState.GUI: self.noteContent.setReadOnly(False) send_button = True self.addButton.show() elif s == MsgState.TO_SEND: send_button = True self.addButton.setDisabled(True) self.sendButton.setDisabled(True) self.noteContent.setReadOnly(True) elif s == MsgState.DELETED: self.close() else: self.sendButton.hide() self.addButton.hide() self.noteContent.setReadOnly(True) if send_button: self.sendButton.show() self.senderUserEntry.setText(trunc_str(self.sender(), 6)) else: self.senderUserEntry.setText(trunc_str(self.sender(), 16)) self.senderUserEntry.setToolTip(self.sender()) def setMessageState(self, state): self.__message__.state = state self.updateMessageState() def setMessage(self, message): assert message self.__message__ = message self.setSender(message.sender) self.setRecipients(message.recipients) self.dateData.setText(message.create_date.strftime(DATETIME_FORMAT)) self.validData.setText(message.expire_date.strftime(DATETIME_FORMAT)) self.noteContent.setHtml(message.content) self.updateMessageState() def sendMessage(self): # tylko dla całkiem nowych wiadomości (w sumie tylko powinny być) if self.__message__.state == MsgState.GUI: self.__message__.content = self.noteContent.toPlainText() self.__message__.sender = self.sender() self.__message__.recipients = self.recipients() self.setMessageState(MsgState.TO_SEND) self.mainGui.client.addMsg(self.__message__) self.mainGui.updateNotes() def getMessage(self): return self.__message__ def sender(self): return self.sender_ def recipients(self): '''Zwraca listę str adresatów''' return self.recipients_ def knownUsers(self): '''Zwraca listę znanych użytkowników''' return self.mainGui.knownUsers() def addKnownUser(self, username): self.mainGui.addKnownUser(username) @Slot() def closeNote(self): '''Dla przycisku zamykania - tylko ustawia stan DELETED. Reszta działań jest obsługiwana przez zmianę stanu''' self.setMessageState(MsgState.DELETED) # TODO: do tego można zrobić inną metodę przesyłającą tylko nowy stan... self.mainGui.client.modMsg(self.__message__) @Slot() def toggleDatesWidget(self, visibility): '''Dla widgetu z datami - przełączanie widoczności''' if visibility: self.datesWidget.show() else: self.datesWidget.hide() @Slot() def selectRecipients(self): if not self.selectRecipentsWindow: self.selectRecipentsWindow = SelectRecipientsWindow(self) self.selectRecipentsWindow.show()
from PySide.QtGui import QPushButton, QLabel from PySide.QtCore import QStateMachine, QState switch = QPushButton("Switch") notification = QLabel("Flip the switch") onState = QState() offState = QState() offState.addTransition(switch, "clicked()", onState) onState.addTransition(switch, "clicked()", offState) offState.assignProperty(notification, "text", "Off") onState.assignProperty(notification, "text", "On") machine = QStateMachine() machine.addState(onState) machine.addState(offState) machine.setInitialState(offState) machine.start() switch.show() notification.show()