class RunConfigDialog(BaseRunConfigDialog): """Run configuration dialog box: multiple file version""" def __init__(self, parent=None): BaseRunConfigDialog.__init__(self, parent) self.file_to_run = None self.combo = None self.stack = None def run_btn_clicked(self): """Run button was just clicked""" self.file_to_run = unicode(self.combo.currentText()) def setup(self, fname): """Setup Run Configuration dialog with filename *fname*""" combo_label = QLabel(_("Select a run configuration:")) self.combo = QComboBox() self.combo.setMaxVisibleItems(20) self.combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength) self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.stack = QStackedWidget() configurations = _get_run_configurations() for index, (filename, options) in enumerate(configurations): if fname == filename: break else: # There is no run configuration for script *fname*: # creating a temporary configuration that will be kept only if # dialog changes are accepted by the user configurations.insert(0, (fname, RunConfiguration(fname).get())) index = 0 for filename, options in configurations: widget = RunConfigOptions(self) widget.set(options) self.combo.addItem(filename) self.stack.addWidget(widget) self.connect(self.combo, SIGNAL("currentIndexChanged(int)"), self.stack.setCurrentIndex) self.combo.setCurrentIndex(index) self.add_widgets(combo_label, self.combo, 10, self.stack) self.add_button_box(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.setWindowTitle(_("Run Settings")) def accept(self): """Reimplement Qt method""" configurations = [] for index in range(self.stack.count()): filename = unicode(self.combo.itemText(index)) runconfigoptions = self.stack.widget(index) if index == self.stack.currentIndex() and\ not runconfigoptions.is_valid(): return options = runconfigoptions.get() configurations.append((filename, options)) _set_run_configurations(configurations) QDialog.accept(self)
class QChatTab(QWidget): def __init__(self, chatWindow, nick): QWidget.__init__(self) self.chatWindow = chatWindow self.nick = nick self.unreadCount = 0 self.widgetStack = QStackedWidget(self) self.widgetStack.addWidget( QNickInputWidget('new_chat.png', 150, self.connectClicked, parent=self)) self.widgetStack.addWidget(QConnectingWidget(self)) self.widgetStack.addWidget( QChatWidget(self.chatWindow.connectionManager, self)) # Skip the chat layout if the nick was given denoting an incoming connection if self.nick is None or self.nick == '': self.widgetStack.setCurrentIndex(0) else: self.widgetStack.setCurrentIndex(2) layout = QHBoxLayout() layout.addWidget(self.widgetStack) self.setLayout(layout) def connectClicked(self, nick): # Check that the nick isn't already connected if self.chatWindow.isNickInTabs(nick): QMessageBox.warning(self, errors.TITLE_ALREADY_CONNECTED, errors.ALREADY_CONNECTED % (nick)) return self.nick = nick self.widgetStack.widget(1).setConnectingToNick(self.nick) self.widgetStack.setCurrentIndex(1) self.chatWindow.connectionManager.openChat(self.nick) def showNowChattingMessage(self): self.widgetStack.setCurrentIndex(2) self.widgetStack.widget(2).showNowChattingMessage(self.nick) def appendMessage(self, message, source): self.widgetStack.widget(2).appendMessage(message, source) def resetOrDisable(self): # If the connecting widget is showing, reset to the nick input widget # If the chat widget is showing, disable it to prevent sending of more messages curWidgetIndex = self.widgetStack.currentIndex() if curWidgetIndex == 1: self.widgetStack.setCurrentIndex(0) elif curWidgetIndex == 2: self.widgetStack.widget(2).disable() def enable(self): self.widgetStack.setCurrentIndex(2) self.widgetStack.widget(2).enable()
class RunConfigDialog(BaseRunConfigDialog): """Run configuration dialog box: multiple file version""" def __init__(self, parent=None): BaseRunConfigDialog.__init__(self, parent) self.file_to_run = None self.combo = None self.stack = None def run_btn_clicked(self): """Run button was just clicked""" self.file_to_run = unicode(self.combo.currentText()) def setup(self, fname): """Setup Run Configuration dialog with filename *fname*""" combo_label = QLabel(_("Select a run configuration:")) self.combo = QComboBox() self.combo.setMaxVisibleItems(20) self.combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength) self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.stack = QStackedWidget() configurations = _get_run_configurations() for index, (filename, options) in enumerate(configurations): if fname == filename: break else: # There is no run configuration for script *fname*: # creating a temporary configuration that will be kept only if # dialog changes are accepted by the user configurations.insert(0, (fname, RunConfiguration(fname).get())) index = 0 for filename, options in configurations: widget = RunConfigOptions(self) widget.set(options) self.combo.addItem(filename) self.stack.addWidget(widget) self.connect(self.combo, SIGNAL("currentIndexChanged(int)"), self.stack.setCurrentIndex) self.combo.setCurrentIndex(index) self.add_widgets(combo_label, self.combo, 10, self.stack) self.add_button_box(QDialogButtonBox.Ok|QDialogButtonBox.Cancel) self.setWindowTitle(_("Run Settings")) def accept(self): """Reimplement Qt method""" configurations = [] for index in range(self.stack.count()): filename = unicode(self.combo.itemText(index)) runconfigoptions = self.stack.widget(index) if index == self.stack.currentIndex() and\ not runconfigoptions.is_valid(): return options = runconfigoptions.get() configurations.append( (filename, options) ) _set_run_configurations(configurations) QDialog.accept(self)
class QChatTab(QWidget): def __init__(self, chatWindow, nick): QWidget.__init__(self) self.chatWindow = chatWindow self.nick = nick self.unreadCount = 0 self.widgetStack = QStackedWidget(self) self.widgetStack.addWidget(QNickInputWidget('new_chat.png', 150, self.connectClicked, parent=self)) self.widgetStack.addWidget(QConnectingWidget(self)) self.widgetStack.addWidget(QChatWidget(self.chatWindow.connectionManager, self)) # Skip the chat layout if the nick was given denoting an incoming connection if self.nick is None or self.nick == '': self.widgetStack.setCurrentIndex(0) else: self.widgetStack.setCurrentIndex(2) layout = QHBoxLayout() layout.addWidget(self.widgetStack) self.setLayout(layout) def connectClicked(self, nick): # Check that the nick isn't already connected if self.chatWindow.isNickInTabs(nick): QMessageBox.warning(self, errors.TITLE_ALREADY_CONNECTED, errors.ALREADY_CONNECTED % (nick)) return self.nick = nick self.widgetStack.widget(1).setConnectingToNick(self.nick) self.widgetStack.setCurrentIndex(1) self.chatWindow.connectionManager.openChat(self.nick) def showNowChattingMessage(self): self.widgetStack.setCurrentIndex(2) self.widgetStack.widget(2).showNowChattingMessage(self.nick) def appendMessage(self, message, source): self.widgetStack.widget(2).appendMessage(message, source) def resetOrDisable(self): # If the connecting widget is showing, reset to the nick input widget # If the chat widget is showing, disable it to prevent sending of more messages curWidgetIndex = self.widgetStack.currentIndex() if curWidgetIndex == 1: self.widgetStack.setCurrentIndex(0) elif curWidgetIndex == 2: self.widgetStack.widget(2).disable() def enable(self): self.widgetStack.setCurrentIndex(2) self.widgetStack.widget(2).enable()
class Declaration(QDialog, ui_declaration.Ui_Declaration): def __init__(self, parent, noi): super(Declaration, self).__init__(parent) self.setupUi(self) self.noidec = noi self.parent = parent self.scenario = parent.scenario self.pages_widget = QStackedWidget() self.connect(self.pages_widget, SIGNAL("currentChanged(int)"), self.current_page_changed) self.connect(self.contents_widget, SIGNAL("currentRowChanged(int)"), self.pages_widget.setCurrentIndex) self.scrollArea.setWidget(self.pages_widget) self.connect(self.next_btn, SIGNAL('clicked()'), self.next_page) self.connect(self.prev_btn, SIGNAL('clicked()'), self.prev_page) self.pages = [Page01(self), Page02(self), Page03(self), Page04(self), Page05(self), Page06(self), Page07(self), PageIsf(self)] for widget in self.pages: self.add_page(widget) self.set_current_index(0) self.current_page_changed(0) def current_page_changed(self, index): nb = self.pages_widget.count() - 1 self.prev_btn.setEnabled(True) self.next_btn.setEnabled(True) if index == nb: self.next_btn.setEnabled(False) if index == 0: self.prev_btn.setEnabled(False) def next_page(self): idx = self.pages_widget.currentIndex() self.set_current_index(idx + 1) def prev_page(self): idx = self.pages_widget.currentIndex() self.set_current_index(idx - 1) def get_current_index(self): """Return current page index""" return self.contents_widget.currentRow() def set_current_index(self, index): """Set current page index""" self.contents_widget.setCurrentRow(index) self.pages_widget.setCurrentIndex(index) def accept(self): for page in self.pages: for key in page.__dict__: widget = getattr(page,key) if isinstance(widget, QSpinBox): var = str(widget.objectName()) val = widget.value() page.updateFoyer(var, val) elif isinstance(widget, QCheckBox): var = str(widget.objectName()) val = 1*(widget.checkState()>=1) page.updateFoyer(var, val) QDialog.accept(self) def add_page(self, widget): self.pages_widget.addWidget(widget) item = QListWidgetItem(self.contents_widget) item.setText(widget.get_name()) item.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
class LunchMenuWidget(QWidget): textViewIndex = 0 textViewAdditivesMap = {} def __init__(self, parent): super(LunchMenuWidget, self).__init__(parent) box = QVBoxLayout(self) box.addWidget(QLabel(u"Initializing...", self)) def initializeLayout(self): layout = self.layout() child = layout.takeAt(0) while child != None: child.widget().deleteLater() child = layout.takeAt(0) self.messages = LunchMenu.messages() self.toggleMessages = LunchMenu.toggleMessages() self.additives = LunchMenu.additives() self.toggleAdditives = LunchMenu.toggleAdditives() buttonBar = self.createButtonBar(self) layout.addLayout(buttonBar) self.menuNotebook = QStackedWidget(self) self.createNotebook() layout.addWidget(self.menuNotebook) self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) def create_arrow_button(self, parent, arrow_type): button = QToolButton(parent) button.setArrowType(arrow_type) return button def goLeft(self): curIndex = self.combobox.currentIndex() if curIndex > 0: self.combobox.setCurrentIndex(curIndex - 1) def goRight(self): curIndex = self.combobox.currentIndex() if curIndex < 4: self.combobox.setCurrentIndex(curIndex + 1) def goToday(self): now = LunchMenu.today() minDelta = sys.maxint minDeltaI = 0 i = 0 for aLunchMenu in LunchMenu.allLunchMenus(): if aLunchMenu == None or isinstance(aLunchMenu, Exception): # parse error, use current day of week if now.weekday() < 5: minDeltaI = now.weekday() else: minDeltaI = 4 break td = now - aLunchMenu.lunchDate delta = abs((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6) if delta < minDelta: minDelta = delta minDeltaI = i i = i + 1 self.combobox.setCurrentIndex(minDeltaI) def goTodayClicked(self): self.goToday() def isToggled(self): index = self.menuNotebook.currentIndex() return (index >= 5) def changed_combo(self, index): if self.isToggled(): self.menuNotebook.setCurrentIndex(index + 5) else: self.menuNotebook.setCurrentIndex(index) self.leftButton.setEnabled(index != 0) self.rightButton.setEnabled(index != 4) def toggleLanguage(self): index = self.menuNotebook.currentIndex() isToggle = (index >= 5) if isToggle: self.switchLanguageButton.setText(self.messages["toggleLanguage"]) index = index - 5 else: self.switchLanguageButton.setText(self.messages["toggleLanguage2"]) index = index + 5 self.menuNotebook.setCurrentIndex(index) def createButtonBar(self, parent): self.combobox = QComboBox(parent) self.combobox.addItem(self.messages['monday']) self.combobox.addItem(self.messages['tuesday']) self.combobox.addItem(self.messages['wednesday']) self.combobox.addItem(self.messages['thursday']) self.combobox.addItem(self.messages['friday']) self.combobox.currentIndexChanged.connect(self.changed_combo) comboBoxHeight = self.combobox.sizeHint().height() self.leftButton = self.create_arrow_button(parent, Qt.LeftArrow) self.leftButton.clicked.connect(self.goLeft) self.leftButton.setMinimumSize(comboBoxHeight, comboBoxHeight) self.rightButton = self.create_arrow_button(parent, Qt.RightArrow) self.rightButton.clicked.connect(self.goRight) self.rightButton.setMinimumSize(comboBoxHeight, comboBoxHeight) navButtons = QHBoxLayout() navButtons.addWidget(self.leftButton, 0, Qt.AlignRight) navButtons.addWidget(self.combobox, 0, Qt.AlignCenter) navButtons.addWidget(self.rightButton, 0, Qt.AlignLeft) buttonBar = QHBoxLayout() todayButton = QPushButton(self.messages['today'], parent) todayButton.clicked.connect(self.goTodayClicked) todayButton.setMinimumHeight(comboBoxHeight) buttonBar.addWidget(todayButton) buttonBar.addWidget(QWidget(parent), 1) buttonBar.addLayout(navButtons, 1) buttonBar.addWidget(QWidget(parent), 1) self.switchLanguageButton = QPushButton( self.messages["toggleLanguage"], parent) self.switchLanguageButton.clicked.connect(self.toggleLanguage) self.switchLanguageButton.setMinimumHeight(comboBoxHeight) buttonBar.addWidget(self.switchLanguageButton, 0, Qt.AlignRight) return buttonBar def addMenuLine(self, parent, text, box, header=False): aLabel = QLabel(text, parent) if header: aLabel.setAlignment(Qt.AlignCenter) oldFont = aLabel.font() aLabel.setFont(QFont(oldFont.family(), 13, QFont.Bold)) box.addWidget(aLabel, 0, Qt.AlignBottom) def addLocaleErrorPage(self, parent, box, toggle): aLabel = QLabel(self.messages['parseLocaleError'], parent) aLabel.setWordWrap(True) box.addWidget(aLabel) aButton = QPushButton(self.messages['installLocaleButton'], parent) if toggle: aButton.clicked.connect(self.installLanguageSupportToggle) else: aButton.clicked.connect(self.installLanguageSupport) box.addWidget(aButton) def addExceptionPage(self, parent, box, error, _toggle): aLabel = QLabel( self.messages['otherException'] + u" " + unicode(error), parent) aLabel.setWordWrap(True) box.addWidget(aLabel) def installLanguageSupportForLocale(self, locale): locale = locale.partition("_")[0] if subprocess.call( ['gksu', "apt-get -q -y install language-pack-%s" % locale]) != 0: QMessageBox().critical(self.menuNotebook, "Installation Error", self.messages['installLocaleError'], buttons=QMessageBox.Ok, defaultButton=QMessageBox.Ok) else: QMessageBox().information(self.menuNotebook, "Success", self.messages['installLocaleSuccess'], buttons=QMessageBox.Ok, defaultButton=QMessageBox.Ok) def installLanguageSupport(self): self.installLanguageSupportForLocale(self.defaultLocaleString) def installLanguageSupportToggle(self): self.installLanguageSupportForLocale(self.messages['toggleLocale']) def formatTitleAndDescription(self, title, description, keyInfo): if title and description: result = "%s, %s" % (title, description) elif title: result = title else: result = description if keyInfo: return "%s: %s" % (keyInfo.title(), result) return result def addMenuContent(self, parent, desc, menuContents, box, messages, additivesDict): self.addMenuLine(parent, desc, box) if desc in menuContents: contentList = menuContents[desc] else: contentList = [(messages[u'noContents'], None, [], None)] log_debug("lunch menu does not contain key '%s'" % desc) textview = GrowingTextEdit(parent, messages, additivesDict) textview.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) textview.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) textview.setLineWrapMode(QTextEdit.WidgetWidth) textview.setReadOnly(True) textview.document().setIndentWidth(10) if len(contentList) == 1: title, description, additives, keyInfo = contentList[0] textview.append( self.formatTitleAndDescription(title, description, keyInfo), additives) elif len(contentList) > 1: cursor = textview.textCursor() listFormat = QTextListFormat() listFormat.setStyle(QTextListFormat.ListDisc) listFormat.setIndent(1) cursor.createList(listFormat) for title, description, additives, keyInfo in contentList: textview.append( self.formatTitleAndDescription(title, description, keyInfo), additives) box.addWidget(textview, 0) def createNotebook(self): self.combobox.setCurrentIndex(0) for _ in range(self.menuNotebook.count()): self.menuNotebook.removeWidget(self.menuNotebook.widget(0)) curMessages = self.messages curAdditives = self.additives for index in range(10): if index == 5: try: if getPlatform() != PLATFORM_WINDOWS: locale.setlocale( locale.LC_TIME, (self.messages["toggleLocale"], "UTF-8")) except: log_exception("error setting locale") curMessages = self.toggleMessages curAdditives = self.toggleAdditives pageWidget = QWidget(self.menuNotebook) page = QVBoxLayout(pageWidget) thisLunchMenu = LunchMenu.allLunchMenus()[index] if thisLunchMenu != None and type(thisLunchMenu) == LunchMenu: title = curMessages[ 'lunchMenuFor'] + u" " + thisLunchMenu.lunchDate.strftime( curMessages['dateFormatDisplayed']).decode("utf-8") self.addMenuLine(pageWidget, title, page, True) if thisLunchMenu.isValid(): self.addMenuContent(pageWidget, curMessages['soupDisplayed'], thisLunchMenu.contents, page, curMessages, curAdditives) self.addMenuContent(pageWidget, curMessages['mainDishesDisplayed'], thisLunchMenu.contents, page, curMessages, curAdditives) self.addMenuContent(pageWidget, curMessages['supplementsDisplayed'], thisLunchMenu.contents, page, curMessages, curAdditives) self.addMenuContent(pageWidget, curMessages['dessertsDisplayed'], thisLunchMenu.contents, page, curMessages, curAdditives) else: self.addMenuLine(pageWidget, curMessages['noLunchToday'], page) elif type(thisLunchMenu) == locale.Error: self.addLocaleErrorPage(pageWidget, page, index >= 5) pass elif isinstance(thisLunchMenu, Exception): self.addExceptionPage(pageWidget, page, thisLunchMenu, index >= 5) self.menuNotebook.addWidget(pageWidget) try: if getPlatform() != PLATFORM_WINDOWS: locale.setlocale(locale.LC_TIME, (LunchMenu.defaultLocaleString, "UTF-8")) except: log_exception("error setting locale") self.goToday()
class E4SideBar(QWidget): """ Class implementing a sidebar with a widget area, that is hidden or shown, if the current tab is clicked again. """ Version = 1 North = 0 East = 1 South = 2 West = 3 def __init__(self, orientation = None, delay = 200, parent = None): """ Constructor @param orientation orientation of the sidebar widget (North, East, South, West) @param delay value for the expand/shrink delay in milliseconds (integer) @param parent parent widget (QWidget) """ QWidget.__init__(self, parent) self.__tabBar = QTabBar() self.__tabBar.setDrawBase(True) self.__tabBar.setShape(QTabBar.RoundedNorth) self.__tabBar.setUsesScrollButtons(True) self.__tabBar.setDrawBase(False) self.__stackedWidget = QStackedWidget(self) self.__stackedWidget.setContentsMargins(0, 0, 0, 0) self.__autoHideButton = QToolButton() self.__autoHideButton.setCheckable(True) self.__autoHideButton.setIcon(UI.PixmapCache.getIcon("autoHideOff.png")) self.__autoHideButton.setChecked(True) self.__autoHideButton.setToolTip( self.trUtf8("Deselect to activate automatic collapsing")) self.barLayout = QBoxLayout(QBoxLayout.LeftToRight) self.barLayout.setMargin(0) self.layout = QBoxLayout(QBoxLayout.TopToBottom) self.layout.setMargin(0) self.layout.setSpacing(0) self.barLayout.addWidget(self.__autoHideButton) self.barLayout.addWidget(self.__tabBar) self.layout.addLayout(self.barLayout) self.layout.addWidget(self.__stackedWidget) self.setLayout(self.layout) # initialize the delay timer self.__actionMethod = None self.__delayTimer = QTimer(self) self.__delayTimer.setSingleShot(True) self.__delayTimer.setInterval(delay) self.connect(self.__delayTimer, SIGNAL("timeout()"), self.__delayedAction) self.__minimized = False self.__minSize = 0 self.__maxSize = 0 self.__bigSize = QSize() self.splitter = None self.splitterSizes = [] self.__hasFocus = False # flag storing if this widget or any child has the focus self.__autoHide = False self.__tabBar.installEventFilter(self) self.__orientation = E4SideBar.North if orientation is None: orientation = E4SideBar.North self.setOrientation(orientation) self.connect(self.__tabBar, SIGNAL("currentChanged(int)"), self.__stackedWidget, SLOT("setCurrentIndex(int)")) self.connect(e4App(), SIGNAL("focusChanged(QWidget*, QWidget*)"), self.__appFocusChanged) self.connect(self.__autoHideButton, SIGNAL("toggled(bool)"), self.__autoHideToggled) def setSplitter(self, splitter): """ Public method to set the splitter managing the sidebar. @param splitter reference to the splitter (QSplitter) """ self.splitter = splitter self.connect(self.splitter, SIGNAL("splitterMoved(int, int)"), self.__splitterMoved) self.splitter.setChildrenCollapsible(False) index = self.splitter.indexOf(self) self.splitter.setCollapsible(index, False) def __splitterMoved(self, pos, index): """ Private slot to react on splitter moves. @param pos new position of the splitter handle (integer) @param index index of the splitter handle (integer) """ if self.splitter: self.splitterSizes = self.splitter.sizes() def __delayedAction(self): """ Private slot to handle the firing of the delay timer. """ if self.__actionMethod is not None: self.__actionMethod() def setDelay(self, delay): """ Public method to set the delay value for the expand/shrink delay in milliseconds. @param delay value for the expand/shrink delay in milliseconds (integer) """ self.__delayTimer.setInterval(delay) def delay(self): """ Public method to get the delay value for the expand/shrink delay in milliseconds. @return value for the expand/shrink delay in milliseconds (integer) """ return self.__delayTimer.interval() def __cancelDelayTimer(self): """ Private method to cancel the current delay timer. """ self.__delayTimer.stop() self.__actionMethod = None def shrink(self): """ Public method to record a shrink request. """ self.__delayTimer.stop() self.__actionMethod = self.__shrinkIt self.__delayTimer.start() def __shrinkIt(self): """ Private method to shrink the sidebar. """ self.__minimized = True self.__bigSize = self.size() if self.__orientation in [E4SideBar.North, E4SideBar.South]: self.__minSize = self.minimumSizeHint().height() self.__maxSize = self.maximumHeight() else: self.__minSize = self.minimumSizeHint().width() self.__maxSize = self.maximumWidth() if self.splitter: self.splitterSizes = self.splitter.sizes() self.__stackedWidget.hide() if self.__orientation in [E4SideBar.North, E4SideBar.South]: self.setFixedHeight(self.__tabBar.minimumSizeHint().height()) else: self.setFixedWidth(self.__tabBar.minimumSizeHint().width()) self.__actionMethod = None def expand(self): """ Private method to record a expand request. """ self.__delayTimer.stop() self.__actionMethod = self.__expandIt self.__delayTimer.start() def __expandIt(self): """ Public method to expand the sidebar. """ self.__minimized = False self.__stackedWidget.show() self.resize(self.__bigSize) if self.__orientation in [E4SideBar.North, E4SideBar.South]: minSize = max(self.__minSize, self.minimumSizeHint().height()) self.setMinimumHeight(minSize) self.setMaximumHeight(self.__maxSize) else: minSize = max(self.__minSize, self.minimumSizeHint().width()) self.setMinimumWidth(minSize) self.setMaximumWidth(self.__maxSize) if self.splitter: self.splitter.setSizes(self.splitterSizes) self.__actionMethod = None def isMinimized(self): """ Public method to check the minimized state. @return flag indicating the minimized state (boolean) """ return self.__minimized def isAutoHiding(self): """ Public method to check, if the auto hide function is active. @return flag indicating the state of auto hiding (boolean) """ return self.__autoHide def eventFilter(self, obj, evt): """ Protected method to handle some events for the tabbar. @param obj reference to the object (QObject) @param evt reference to the event object (QEvent) @return flag indicating, if the event was handled (boolean) """ if obj == self.__tabBar: if evt.type() == QEvent.MouseButtonPress: pos = evt.pos() for i in range(self.__tabBar.count()): if self.__tabBar.tabRect(i).contains(pos): break if i == self.__tabBar.currentIndex(): if self.isMinimized(): self.expand() else: self.shrink() return True elif self.isMinimized(): self.expand() elif evt.type() == QEvent.Wheel and not self.__stackedWidget.isHidden(): if evt.delta() > 0: self.prevTab() else: self.nextTab() return True return QWidget.eventFilter(self, obj, evt) def addTab(self, widget, iconOrLabel, label = None): """ Public method to add a tab to the sidebar. @param widget reference to the widget to add (QWidget) @param iconOrLabel reference to the icon or the labeltext of the tab (QIcon, string or QString) @param label the labeltext of the tab (string or QString) (only to be used, if the second parameter is a QIcon) """ if label: index = self.__tabBar.addTab(iconOrLabel, label) self.__tabBar.setTabToolTip(index, label) else: index = self.__tabBar.addTab(iconOrLabel) self.__tabBar.setTabToolTip(index, iconOrLabel) self.__stackedWidget.addWidget(widget) if self.__orientation in [E4SideBar.North, E4SideBar.South]: self.__minSize = self.minimumSizeHint().height() else: self.__minSize = self.minimumSizeHint().width() def insertTab(self, index, widget, iconOrLabel, label = None): """ Public method to insert a tab into the sidebar. @param index the index to insert the tab at (integer) @param widget reference to the widget to insert (QWidget) @param iconOrLabel reference to the icon or the labeltext of the tab (QIcon, string or QString) @param label the labeltext of the tab (string or QString) (only to be used, if the second parameter is a QIcon) """ if label: index = self.__tabBar.insertTab(index, iconOrLabel, label) self.__tabBar.setTabToolTip(index, label) else: index = self.__tabBar.insertTab(index, iconOrLabel) self.__tabBar.setTabToolTip(index, iconOrLabel) self.__stackedWidget.insertWidget(index, widget) if self.__orientation in [E4SideBar.North, E4SideBar.South]: self.__minSize = self.minimumSizeHint().height() else: self.__minSize = self.minimumSizeHint().width() def removeTab(self, index): """ Public method to remove a tab. @param index the index of the tab to remove (integer) """ self.__stackedWidget.removeWidget(self.__stackedWidget.widget(index)) self.__tabBar.removeTab(index) if self.__orientation in [E4SideBar.North, E4SideBar.South]: self.__minSize = self.minimumSizeHint().height() else: self.__minSize = self.minimumSizeHint().width() def clear(self): """ Public method to remove all tabs. """ while self.count() > 0: self.removeTab(0) def prevTab(self): """ Public slot used to show the previous tab. """ ind = self.currentIndex() - 1 if ind == -1: ind = self.count() - 1 self.setCurrentIndex(ind) self.currentWidget().setFocus() def nextTab(self): """ Public slot used to show the next tab. """ ind = self.currentIndex() + 1 if ind == self.count(): ind = 0 self.setCurrentIndex(ind) self.currentWidget().setFocus() def count(self): """ Public method to get the number of tabs. @return number of tabs in the sidebar (integer) """ return self.__tabBar.count() def currentIndex(self): """ Public method to get the index of the current tab. @return index of the current tab (integer) """ return self.__stackedWidget.currentIndex() def setCurrentIndex(self, index): """ Public slot to set the current index. @param index the index to set as the current index (integer) """ self.__tabBar.setCurrentIndex(index) self.__stackedWidget.setCurrentIndex(index) if self.isMinimized(): self.expand() def currentWidget(self): """ Public method to get a reference to the current widget. @return reference to the current widget (QWidget) """ return self.__stackedWidget.currentWidget() def setCurrentWidget(self, widget): """ Public slot to set the current widget. @param widget reference to the widget to become the current widget (QWidget) """ self.__stackedWidget.setCurrentWidget(widget) self.__tabBar.setCurrentIndex(self.__stackedWidget.currentIndex()) if self.isMinimized(): self.expand() def indexOf(self, widget): """ Public method to get the index of the given widget. @param widget reference to the widget to get the index of (QWidget) @return index of the given widget (integer) """ return self.__stackedWidget.indexOf(widget) def isTabEnabled(self, index): """ Public method to check, if a tab is enabled. @param index index of the tab to check (integer) @return flag indicating the enabled state (boolean) """ return self.__tabBar.isTabEnabled(index) def setTabEnabled(self, index, enabled): """ Public method to set the enabled state of a tab. @param index index of the tab to set (integer) @param enabled enabled state to set (boolean) """ self.__tabBar.setTabEnabled(index, enabled) def orientation(self): """ Public method to get the orientation of the sidebar. @return orientation of the sidebar (North, East, South, West) """ return self.__orientation def setOrientation(self, orient): """ Public method to set the orientation of the sidebar. @param orient orientation of the sidebar (North, East, South, West) """ if orient == E4SideBar.North: self.__tabBar.setShape(QTabBar.RoundedNorth) self.__tabBar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.barLayout.setDirection(QBoxLayout.LeftToRight) self.layout.setDirection(QBoxLayout.TopToBottom) self.layout.setAlignment(self.barLayout, Qt.AlignLeft) elif orient == E4SideBar.East: self.__tabBar.setShape(QTabBar.RoundedEast) self.__tabBar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.barLayout.setDirection(QBoxLayout.TopToBottom) self.layout.setDirection(QBoxLayout.RightToLeft) self.layout.setAlignment(self.barLayout, Qt.AlignTop) elif orient == E4SideBar.South: self.__tabBar.setShape(QTabBar.RoundedSouth) self.__tabBar.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.barLayout.setDirection(QBoxLayout.LeftToRight) self.layout.setDirection(QBoxLayout.BottomToTop) self.layout.setAlignment(self.barLayout, Qt.AlignLeft) elif orient == E4SideBar.West: self.__tabBar.setShape(QTabBar.RoundedWest) self.__tabBar.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.barLayout.setDirection(QBoxLayout.TopToBottom) self.layout.setDirection(QBoxLayout.LeftToRight) self.layout.setAlignment(self.barLayout, Qt.AlignTop) self.__orientation = orient def tabIcon(self, index): """ Public method to get the icon of a tab. @param index index of the tab (integer) @return icon of the tab (QIcon) """ return self.__tabBar.tabIcon(index) def setTabIcon(self, index, icon): """ Public method to set the icon of a tab. @param index index of the tab (integer) @param icon icon to be set (QIcon) """ self.__tabBar.setTabIcon(index, icon) def tabText(self, index): """ Public method to get the text of a tab. @param index index of the tab (integer) @return text of the tab (QString) """ return self.__tabBar.tabText(index) def setTabText(self, index, text): """ Public method to set the text of a tab. @param index index of the tab (integer) @param text text to set (QString) """ self.__tabBar.setTabText(index, text) def tabToolTip(self, index): """ Public method to get the tooltip text of a tab. @param index index of the tab (integer) @return tooltip text of the tab (QString) """ return self.__tabBar.tabToolTip(index) def setTabToolTip(self, index, tip): """ Public method to set the tooltip text of a tab. @param index index of the tab (integer) @param tooltip text text to set (QString) """ self.__tabBar.setTabToolTip(index, tip) def tabWhatsThis(self, index): """ Public method to get the WhatsThis text of a tab. @param index index of the tab (integer) @return WhatsThis text of the tab (QString) """ return self.__tabBar.tabWhatsThis(index) def setTabWhatsThis(self, index, text): """ Public method to set the WhatsThis text of a tab. @param index index of the tab (integer) @param WhatsThis text text to set (QString) """ self.__tabBar.setTabWhatsThis(index, text) def widget(self, index): """ Public method to get a reference to the widget associated with a tab. @param index index of the tab (integer) @return reference to the widget (QWidget) """ return self.__stackedWidget.widget(index) def saveState(self): """ Public method to save the state of the sidebar. @return saved state as a byte array (QByteArray) """ if len(self.splitterSizes) == 0: if self.splitter: self.splitterSizes = self.splitter.sizes() self.__bigSize = self.size() if self.__orientation in [E4SideBar.North, E4SideBar.South]: self.__minSize = self.minimumSizeHint().height() self.__maxSize = self.maximumHeight() else: self.__minSize = self.minimumSizeHint().width() self.__maxSize = self.maximumWidth() data = QByteArray() stream = QDataStream(data, QIODevice.WriteOnly) stream.writeUInt16(self.Version) stream.writeBool(self.__minimized) stream << self.__bigSize stream.writeUInt16(self.__minSize) stream.writeUInt16(self.__maxSize) stream.writeUInt16(len(self.splitterSizes)) for size in self.splitterSizes: stream.writeUInt16(size) stream.writeBool(self.__autoHide) return data def restoreState(self, state): """ Public method to restore the state of the sidebar. @param state byte array containing the saved state (QByteArray) @return flag indicating success (boolean) """ if state.isEmpty(): return False if self.__orientation in [E4SideBar.North, E4SideBar.South]: minSize = self.layout.minimumSize().height() maxSize = self.maximumHeight() else: minSize = self.layout.minimumSize().width() maxSize = self.maximumWidth() data = QByteArray(state) stream = QDataStream(data, QIODevice.ReadOnly) stream.readUInt16() # version minimized = stream.readBool() if minimized: self.shrink() stream >> self.__bigSize self.__minSize = max(stream.readUInt16(), minSize) self.__maxSize = max(stream.readUInt16(), maxSize) count = stream.readUInt16() self.splitterSizes = [] for i in range(count): self.splitterSizes.append(stream.readUInt16()) self.__autoHide = stream.readBool() self.__autoHideButton.setChecked(not self.__autoHide) if not minimized: self.expand() return True ####################################################################### ## methods below implement the autohide functionality ####################################################################### def __autoHideToggled(self, checked): """ Private slot to handle the toggling of the autohide button. @param checked flag indicating the checked state of the button (boolean) """ self.__autoHide = not checked if self.__autoHide: self.__autoHideButton.setIcon(UI.PixmapCache.getIcon("autoHideOn.png")) else: self.__autoHideButton.setIcon(UI.PixmapCache.getIcon("autoHideOff.png")) def __appFocusChanged(self, old, now): """ Private slot to handle a change of the focus. @param old reference to the widget, that lost focus (QWidget or None) @param now reference to the widget having the focus (QWidget or None) """ self.__hasFocus = self.isAncestorOf(now) if self.__autoHide and not self.__hasFocus and not self.isMinimized(): self.shrink() elif self.__autoHide and self.__hasFocus and self.isMinimized(): self.expand() def enterEvent(self, event): """ Protected method to handle the mouse entering this widget. @param event reference to the event (QEvent) """ if self.__autoHide and self.isMinimized(): self.expand() else: self.__cancelDelayTimer() def leaveEvent(self, event): """ Protected method to handle the mouse leaving this widget. @param event reference to the event (QEvent) """ if self.__autoHide and not self.__hasFocus and not self.isMinimized(): self.shrink() else: self.__cancelDelayTimer() def shutdown(self): """ Public method to shut down the object. This method does some preparations so the object can be deleted properly. It disconnects from the focusChanged signal in order to avoid trouble later on. """ self.disconnect(e4App(), SIGNAL("focusChanged(QWidget*, QWidget*)"), self.__appFocusChanged)
class EditorWidget(QWidget): # Señales allFilesClosed = pyqtSignal() def __init__(self): super(EditorWidget, self).__init__() self._recents_files = [] box = QVBoxLayout(self) box.setContentsMargins(0, 0, 0, 0) box.setSpacing(0) # Combo container self.combo = ComboContainer(self) box.addWidget(self.combo) # Stacked self.stack = QStackedWidget() box.addWidget(self.stack) self.connect(self.combo.combo_file, SIGNAL("currentIndexChanged(int)"), self.change_item) def add_widget(self, widget): index = self.stack.addWidget(widget) if not self.combo.isVisible(): self.combo.setVisible(True) self.stack.setCurrentIndex(index) def add_item_combo(self, text): self.combo.combo_file.addItem(text) self.combo.combo_file.setCurrentIndex( self.combo.combo_file.count() - 1) def remove_item_combo(self, index): self.combo.combo_file.removeItem(index) def change_item(self, index): self.stack.setCurrentIndex(index) self.emit(SIGNAL("currentWidgetChanged(int)"), index) def current_widget(self): return self.stack.currentWidget() def current_index(self): return self.stack.currentIndex() def widget(self, index): return self.stack.widget(index) def count(self): return self.stack.count() def close_file(self): self.remove_widget(self.current_widget(), self.current_index()) def close_file_project(self, widget, index): #FIXME: unir con close file self.remove_widget(widget, index) def close_all(self): for index in range(self.count()): self.remove_widget(self.current_widget(), 0) def editor_modified(self, value): weditor = self.current_widget() index = self.current_index() self.combo.set_modified(weditor, index, value) def _add_to_recent(self, filename): if filename == 'Untitled': return if filename not in self._recents_files: self._recents_files.append(filename) self.emit(SIGNAL("recentFile(QStringList)"), self._recents_files) def check_files_not_saved(self): value = False for index in range(self.count()): weditor = self.widget(index) value = value or weditor.is_modified return value def files_not_saved(self): files = [] for index in range(self.count()): weditor = self.widget(index) if weditor.is_modified: files.append(weditor.filename) return files def opened_files(self): files = [] for index in range(self.count()): weditor = self.widget(index) path = weditor.filename if path == 'Untitled': continue files.append(path) return files def remove_widget(self, widget, index): if not isinstance(widget, editor.Editor): return if index != -1: self.stack.setCurrentIndex(index) flags = QMessageBox.Yes flags |= QMessageBox.No flags |= QMessageBox.Cancel result = QMessageBox.No if widget.is_modified: result = QMessageBox.question(self, self.tr( "Archivo no guardado!"), self.tr("El archivo <b>{0}</b> " "tiene cambios sin guardar. " "Quieres guardarlos?").format(widget.filename), QMessageBox.Yes, QMessageBox.No, QMessageBox.Cancel) if result == QMessageBox.Cancel: return elif result == QMessageBox.Yes: self.emit(SIGNAL("saveCurrentFile()")) self._add_to_recent(widget.filename) self.stack.removeWidget(widget) self.emit(SIGNAL("fileClosed(int)"), index) self.remove_item_combo(index) widget.obj_file.stop_system_watcher() if self.current_widget() is not None: self.current_widget().setFocus() else: self.allFilesClosed.emit() def add_symbols(self, symbols): self.combo.add_symbols_combo(symbols)
class LunchMenuWidget(QWidget): textViewIndex = 0 textViewAdditivesMap = {} def __init__(self, parent): super(LunchMenuWidget, self).__init__(parent) box = QVBoxLayout(self) box.addWidget(QLabel(u"Initializing...", self)) def initializeLayout(self): layout = self.layout() child = layout.takeAt(0) while child != None: child.widget().deleteLater() child = layout.takeAt(0) self.messages = LunchMenu.messages() self.toggleMessages = LunchMenu.toggleMessages() self.additives = LunchMenu.additives() self.toggleAdditives = LunchMenu.toggleAdditives() buttonBar = self.createButtonBar(self) layout.addLayout(buttonBar) self.menuNotebook = QStackedWidget(self) self.createNotebook() layout.addWidget(self.menuNotebook) self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) def create_arrow_button(self, parent, arrow_type): button = QToolButton(parent) button.setArrowType(arrow_type) return button def goLeft(self): curIndex = self.combobox.currentIndex() if curIndex > 0: self.combobox.setCurrentIndex(curIndex - 1) def goRight(self): curIndex = self.combobox.currentIndex() if curIndex < 4: self.combobox.setCurrentIndex(curIndex + 1) def goToday(self): now = LunchMenu.today() minDelta = sys.maxint minDeltaI = 0 i = 0 for aLunchMenu in LunchMenu.allLunchMenus(): if aLunchMenu == None or isinstance(aLunchMenu, Exception): # parse error, use current day of week if now.weekday() < 5: minDeltaI = now.weekday() else: minDeltaI = 4 break td = now - aLunchMenu.lunchDate delta = abs((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6) if delta < minDelta: minDelta = delta minDeltaI = i i = i + 1 self.combobox.setCurrentIndex(minDeltaI) def goTodayClicked(self): self.goToday() def isToggled(self): index = self.menuNotebook.currentIndex() return (index >= 5) def changed_combo(self,index): if self.isToggled(): self.menuNotebook.setCurrentIndex(index + 5) else: self.menuNotebook.setCurrentIndex(index) self.leftButton.setEnabled(index != 0) self.rightButton.setEnabled(index != 4) def toggleLanguage(self): index = self.menuNotebook.currentIndex() isToggle = (index >= 5) if isToggle: self.switchLanguageButton.setText(self.messages["toggleLanguage"]) index = index - 5 else: self.switchLanguageButton.setText(self.messages["toggleLanguage2"]) index = index + 5 self.menuNotebook.setCurrentIndex(index) def createButtonBar(self, parent): self.combobox = QComboBox(parent) self.combobox.addItem(self.messages['monday']) self.combobox.addItem(self.messages['tuesday']) self.combobox.addItem(self.messages['wednesday']) self.combobox.addItem(self.messages['thursday']) self.combobox.addItem(self.messages['friday']) self.combobox.currentIndexChanged.connect(self.changed_combo) comboBoxHeight = self.combobox.sizeHint().height() self.leftButton = self.create_arrow_button(parent, Qt.LeftArrow) self.leftButton.clicked.connect(self.goLeft) self.leftButton.setMinimumSize(comboBoxHeight, comboBoxHeight) self.rightButton = self.create_arrow_button(parent, Qt.RightArrow) self.rightButton.clicked.connect(self.goRight) self.rightButton.setMinimumSize(comboBoxHeight, comboBoxHeight) navButtons = QHBoxLayout() navButtons.addWidget(self.leftButton, 0, Qt.AlignRight) navButtons.addWidget(self.combobox, 0, Qt.AlignCenter) navButtons.addWidget(self.rightButton, 0, Qt.AlignLeft) buttonBar = QHBoxLayout() todayButton = QPushButton(self.messages['today'], parent) todayButton.clicked.connect(self.goTodayClicked) todayButton.setMinimumHeight(comboBoxHeight) buttonBar.addWidget(todayButton) buttonBar.addWidget(QWidget(parent), 1) buttonBar.addLayout(navButtons, 1) buttonBar.addWidget(QWidget(parent), 1) self.switchLanguageButton = QPushButton(self.messages["toggleLanguage"], parent) self.switchLanguageButton.clicked.connect(self.toggleLanguage) self.switchLanguageButton.setMinimumHeight(comboBoxHeight) buttonBar.addWidget(self.switchLanguageButton, 0, Qt.AlignRight) return buttonBar def addMenuLine(self, parent, text, box, header = False): aLabel = QLabel(text, parent) if header: aLabel.setAlignment(Qt.AlignCenter) oldFont = aLabel.font() aLabel.setFont(QFont(oldFont.family(), 13, QFont.Bold)) box.addWidget(aLabel, 0, Qt.AlignBottom) def addLocaleErrorPage(self, parent, box, toggle): aLabel = QLabel(self.messages['parseLocaleError'], parent) aLabel.setWordWrap(True) box.addWidget(aLabel) aButton = QPushButton(self.messages['installLocaleButton'], parent) if toggle: aButton.clicked.connect(self.installLanguageSupportToggle) else: aButton.clicked.connect(self.installLanguageSupport) box.addWidget(aButton) def addExceptionPage(self, parent, box, error, _toggle): aLabel = QLabel(self.messages['otherException'] + u" " + unicode(error), parent) aLabel.setWordWrap(True) box.addWidget(aLabel) def installLanguageSupportForLocale(self, locale): locale = locale.partition("_")[0] if subprocess.call(['gksu', "apt-get -q -y install language-pack-%s" % locale])!=0: QMessageBox().critical(self.menuNotebook, "Installation Error", self.messages['installLocaleError'], buttons=QMessageBox.Ok, defaultButton=QMessageBox.Ok) else: QMessageBox().information(self.menuNotebook, "Success", self.messages['installLocaleSuccess'], buttons=QMessageBox.Ok, defaultButton=QMessageBox.Ok) def installLanguageSupport(self): self.installLanguageSupportForLocale(self.defaultLocaleString) def installLanguageSupportToggle(self): self.installLanguageSupportForLocale(self.messages['toggleLocale']) def formatTitleAndDescription(self, title, description, keyInfo): if title and description: result = "%s, %s" % (title, description) elif title: result = title else: result = description if keyInfo: return "%s: %s" % (keyInfo.title(), result) return result def addMenuContent(self, parent, desc, menuContents, box, messages, additivesDict): self.addMenuLine(parent, desc, box) if desc in menuContents: contentList = menuContents[desc] else: contentList = [(messages[u'noContents'], None, [], None)] log_debug("lunch menu does not contain key '%s'" % desc) textview = GrowingTextEdit(parent, messages, additivesDict) textview.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) textview.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) textview.setLineWrapMode(QTextEdit.WidgetWidth) textview.setReadOnly(True) textview.document().setIndentWidth(10) if len(contentList) == 1: title, description, additives, keyInfo = contentList[0] textview.append(self.formatTitleAndDescription(title, description, keyInfo), additives) elif len(contentList) > 1: cursor = textview.textCursor() listFormat = QTextListFormat() listFormat.setStyle(QTextListFormat.ListDisc) listFormat.setIndent(1) cursor.createList(listFormat) for title, description, additives, keyInfo in contentList: textview.append(self.formatTitleAndDescription(title, description, keyInfo), additives) box.addWidget(textview, 0) def createNotebook(self): self.combobox.setCurrentIndex(0) for _ in range(self.menuNotebook.count()): self.menuNotebook.removeWidget(self.menuNotebook.widget(0)) curMessages = self.messages curAdditives = self.additives for index in range(10): if index == 5: try: if getPlatform() != PLATFORM_WINDOWS: locale.setlocale(locale.LC_TIME, (self.messages["toggleLocale"],"UTF-8")) except: log_exception("error setting locale") curMessages = self.toggleMessages curAdditives = self.toggleAdditives pageWidget = QWidget(self.menuNotebook) page = QVBoxLayout(pageWidget) thisLunchMenu = LunchMenu.allLunchMenus()[index] if thisLunchMenu != None and type(thisLunchMenu) == LunchMenu: title = curMessages['lunchMenuFor'] + u" " + thisLunchMenu.lunchDate.strftime(curMessages['dateFormatDisplayed']).decode("utf-8") self.addMenuLine(pageWidget, title, page, True) if thisLunchMenu.isValid(): self.addMenuContent(pageWidget, curMessages['soupDisplayed'], thisLunchMenu.contents, page, curMessages, curAdditives) self.addMenuContent(pageWidget, curMessages['mainDishesDisplayed'], thisLunchMenu.contents, page, curMessages, curAdditives) self.addMenuContent(pageWidget, curMessages['supplementsDisplayed'], thisLunchMenu.contents, page, curMessages, curAdditives) self.addMenuContent(pageWidget, curMessages['dessertsDisplayed'], thisLunchMenu.contents, page, curMessages, curAdditives) else: self.addMenuLine(pageWidget, curMessages['noLunchToday'], page) elif type(thisLunchMenu) == locale.Error: self.addLocaleErrorPage(pageWidget, page, index >= 5) pass elif isinstance(thisLunchMenu, Exception): self.addExceptionPage(pageWidget, page, thisLunchMenu, index >= 5) self.menuNotebook.addWidget(pageWidget) try: if getPlatform() != PLATFORM_WINDOWS: locale.setlocale(locale.LC_TIME, (LunchMenu.defaultLocaleString,"UTF-8")) except: log_exception("error setting locale") self.goToday()
class SideBar(QWidget): """ Sidebar with a widget area which is hidden or shown. On by clicking any tab, off by clicking the current tab. """ North = 0 East = 1 South = 2 West = 3 def __init__(self, orientation=2, parent=None): QWidget.__init__(self, parent) self.__tabBar = QTabBar() self.__tabBar.setDrawBase(True) self.__tabBar.setShape(QTabBar.RoundedNorth) self.__tabBar.setFocusPolicy(Qt.NoFocus) self.__tabBar.setUsesScrollButtons(True) self.__tabBar.setElideMode(1) self.__stackedWidget = QStackedWidget(self) self.__stackedWidget.setContentsMargins(0, 0, 0, 0) self.barLayout = QBoxLayout(QBoxLayout.LeftToRight) self.barLayout.setMargin(0) self.layout = QBoxLayout(QBoxLayout.TopToBottom) self.layout.setMargin(0) self.layout.setSpacing(0) self.barLayout.addWidget(self.__tabBar) self.layout.addLayout(self.barLayout) self.layout.addWidget(self.__stackedWidget) self.setLayout(self.layout) self.__minimized = False self.__minSize = 0 self.__maxSize = 0 self.__bigSize = QSize() self.splitter = None self.__tabBar.installEventFilter(self) self.__orientation = orientation self.setOrientation(orientation) self.__tabBar.currentChanged.connect( self.__stackedWidget.setCurrentIndex) return def setSplitter(self, splitter): """ Set the splitter managing the sidebar """ self.splitter = splitter return def __getIndex(self): " Provides the widget index in splitters " if self.__orientation == SideBar.West: return 0 if self.__orientation == SideBar.East: return 2 if self.__orientation == SideBar.South: return 1 return 0 def __getWidget(self): " Provides a reference to the widget " return self.splitter.widget(self.__getIndex()) def shrink(self): """ Shrink the sidebar """ if self.__minimized: return self.__minimized = True self.__bigSize = self.size() if self.__orientation in [SideBar.North, SideBar.South]: self.__minSize = self.minimumHeight() self.__maxSize = self.maximumHeight() else: self.__minSize = self.minimumWidth() self.__maxSize = self.maximumWidth() self.__stackedWidget.hide() sizes = self.splitter.sizes() selfIndex = self.__getIndex() if self.__orientation in [SideBar.North, SideBar.South]: newHeight = self.__tabBar.minimumSizeHint().height() self.setFixedHeight(newHeight) diff = sizes[selfIndex] - newHeight sizes[selfIndex] = newHeight else: newWidth = self.__tabBar.minimumSizeHint().width() self.setFixedWidth(newWidth) diff = sizes[selfIndex] - newWidth sizes[selfIndex] = newWidth if selfIndex == 0: sizes[1] += diff else: sizes[selfIndex - 1] += diff self.splitter.setSizes(sizes) return def expand(self): """ Expand the sidebar """ if not self.__minimized: return self.__minimized = False self.__stackedWidget.show() self.resize(self.__bigSize) sizes = self.splitter.sizes() selfIndex = self.__getIndex() if self.__orientation in [SideBar.North, SideBar.South]: self.setMinimumHeight(self.__minSize) self.setMaximumHeight(self.__maxSize) diff = self.__bigSize.height() - sizes[selfIndex] sizes[selfIndex] = self.__bigSize.height() else: self.setMinimumWidth(self.__minSize) self.setMaximumWidth(self.__maxSize) diff = self.__bigSize.width() - sizes[selfIndex] sizes[selfIndex] = self.__bigSize.width() if selfIndex == 0: sizes[1] -= diff else: sizes[selfIndex - 1] -= diff self.splitter.setSizes(sizes) return def isMinimized(self): """ Provides the minimized state """ return self.__minimized def eventFilter(self, obj, evt): """ Handle click events for the tabbar """ if obj == self.__tabBar: if evt.type() == QEvent.MouseButtonPress: pos = evt.pos() index = self.__tabBar.count() - 1 while index >= 0: if self.__tabBar.tabRect(index).contains(pos): break index -= 1 if index == self.__tabBar.currentIndex(): if self.isMinimized(): self.expand() else: self.shrink() return True elif self.isMinimized(): if self.isTabEnabled(index): self.expand() return QWidget.eventFilter(self, obj, evt) def addTab(self, widget, iconOrLabel, label=None): """ Add a tab to the sidebar """ if label: self.__tabBar.addTab(iconOrLabel, label) else: self.__tabBar.addTab(iconOrLabel) self.__stackedWidget.addWidget(widget) return def insertTab(self, index, widget, iconOrLabel, label=None): """ Insert a tab into the sidebar """ if label: self.__tabBar.insertTab(index, iconOrLabel, label) else: self.__tabBar.insertTab(index, iconOrLabel) self.__stackedWidget.insertWidget(index, widget) return def removeTab(self, index): """ Remove a tab """ self.__stackedWidget.removeWidget(self.__stackedWidget.widget(index)) self.__tabBar.removeTab(index) return def clear(self): """ Remove all tabs """ while self.count() > 0: self.removeTab(0) return def prevTab(self): """ Show the previous tab """ index = self.currentIndex() - 1 if index < 0: index = self.count() - 1 self.setCurrentIndex(index) self.currentWidget().setFocus() return def nextTab(self): """ Show the next tab """ index = self.currentIndex() + 1 if index >= self.count(): index = 0 self.setCurrentIndex(index) self.currentWidget().setFocus() return def count(self): """ Provides the number of tabs """ return self.__tabBar.count() def currentIndex(self): """ Provides the index of the current tab """ return self.__stackedWidget.currentIndex() def setCurrentIndex(self, index): """ Switch to the certain tab """ if index >= self.currentIndex(): return self.__tabBar.setCurrentIndex(index) self.__stackedWidget.setCurrentIndex(index) if self.isMinimized(): self.expand() return def currentWidget(self): """ Provide a reference to the current widget """ return self.__stackedWidget.currentWidget() def setCurrentWidget(self, widget): """ Set the current widget """ self.__stackedWidget.setCurrentWidget(widget) self.__tabBar.setCurrentIndex(self.__stackedWidget.currentIndex()) if self.isMinimized(): self.expand() return def indexOf(self, widget): """ Provides the index of the given widget """ return self.__stackedWidget.indexOf(widget) def isTabEnabled(self, index): """ Check if the tab is enabled """ return self.__tabBar.isTabEnabled(index) def setTabEnabled(self, index, enabled): """ Set the enabled state of the tab """ self.__tabBar.setTabEnabled(index, enabled) return def orientation(self): """ Provides the orientation of the sidebar """ return self.__orientation def setOrientation(self, orient): """ Set the orientation of the sidebar """ if orient == SideBar.North: self.__tabBar.setShape(QTabBar.RoundedNorth) self.barLayout.setDirection(QBoxLayout.LeftToRight) self.layout.setDirection(QBoxLayout.TopToBottom) self.layout.setAlignment(self.barLayout, Qt.AlignLeft) elif orient == SideBar.East: self.__tabBar.setShape(QTabBar.RoundedEast) self.barLayout.setDirection(QBoxLayout.TopToBottom) self.layout.setDirection(QBoxLayout.RightToLeft) self.layout.setAlignment(self.barLayout, Qt.AlignTop) elif orient == SideBar.South: self.__tabBar.setShape(QTabBar.RoundedSouth) self.barLayout.setDirection(QBoxLayout.LeftToRight) self.layout.setDirection(QBoxLayout.BottomToTop) self.layout.setAlignment(self.barLayout, Qt.AlignLeft) else: # default orient = SideBar.West self.__tabBar.setShape(QTabBar.RoundedWest) self.barLayout.setDirection(QBoxLayout.TopToBottom) self.layout.setDirection(QBoxLayout.LeftToRight) self.layout.setAlignment(self.barLayout, Qt.AlignTop) self.__orientation = orient return def tabIcon(self, index): """ Provide the icon of the tab """ return self.__tabBar.tabIcon(index) def setTabIcon(self, index, icon): """ Set the icon of the tab """ self.__tabBar.setTabIcon(index, icon) return def tabText(self, index): """ Provide the text of the tab """ return self.__tabBar.tabText(index) def setTabText(self, index, text): """ Set the text of the tab """ self.__tabBar.setTabText(index, text) return def tabToolTip(self, index): """ Provide the tooltip text of the tab """ return self.__tabBar.tabToolTip(index) def setTabToolTip(self, index, tip): """ Set the tooltip text of the tab """ self.__tabBar.setTabToolTip(index, tip) return def tabWhatsThis(self, index): """ Provide the WhatsThis text of the tab """ return self.__tabBar.tabWhatsThis(index) def setTabWhatsThis(self, index, text): """ Set the WhatsThis text for the tab """ self.__tabBar.setTabWhatsThis(index, text) return def widget(self, index): """ Provides the reference to the widget (QWidget) """ return self.__stackedWidget.widget(index)
class LayerImportBrowser(QDialog): class VectorPage(QWidget): def __init__(self, parent=None, filters="", encodings=[]): QWidget.__init__(self, parent) self.filters = filters self.layerLineEdit = QLineEdit() self.browseToolButton = QToolButton() self.browseToolButton.setAutoRaise(True) self.browseToolButton.setIcon(QIcon(":document-open")) layerLabel = QLabel("&Dataset:") layerLabel.setBuddy(self.layerLineEdit) self.encodingComboBox = QComboBox() self.encodingComboBox.addItems(encodings) encodingLabel = QLabel("&Encoding:") encodingLabel.setBuddy(self.encodingComboBox) hbox = QHBoxLayout() hbox.addWidget(layerLabel) hbox.addWidget(self.layerLineEdit) hbox.addWidget(self.browseToolButton) vbox = QVBoxLayout() vbox.addLayout(hbox) hbox = QHBoxLayout() hbox.addWidget(encodingLabel) hbox.addWidget(self.encodingComboBox) vbox.addLayout(hbox) self.setLayout(vbox) self.encodingComboBox.setCurrentIndex(self.encodingComboBox.findText("System")) self.connect(self.browseToolButton, SIGNAL("clicked()"), self.browseToFile) self.connect(self.encodingComboBox, SIGNAL("currentIndexChanged(QString)"), self.changeEncoding) def browseToFile(self): dialog = QFileDialog(self, "manageR - Open Vector File", unicode(robjects.r.getwd()[0]), self.filters) if not dialog.exec_() == QDialog.Accepted: return files = dialog.selectedFiles() file = files.first().trimmed() self.layerLineEdit.setText(file) self.emit(SIGNAL("filePathChanged(QString)"), file) def changeEncoding(self, text): self.emit(SIGNAL("encodingChanged(QString)"), text) class RasterPage(QWidget): def __init__(self, parent=None, filters=""): QWidget.__init__(self, parent) self.parent = parent self.filters = filters self.layerLineEdit = QLineEdit() self.browseToolButton = QToolButton() self.browseToolButton.setAutoRaise(True) self.browseToolButton.setIcon(QIcon(":document-open")) layerLabel = QLabel("&Dataset:") layerLabel.setBuddy(self.layerLineEdit) hbox = QHBoxLayout() hbox.addWidget(layerLabel) hbox.addWidget(self.layerLineEdit) hbox.addWidget(self.browseToolButton) vbox = QVBoxLayout() vbox.addLayout(hbox) self.setLayout(vbox) self.connect(self.browseToolButton, SIGNAL("clicked()"), self.browseToFile) def browseToFile(self): dialog = QFileDialog(self, "manageR - Open Raster File", unicode(robjects.r.getwd()[0]), self.filters) if not dialog.exec_() == QDialog.Accepted: return files = dialog.selectedFiles() file = files.first().trimmed() self.layerLineEdit.setText(file) self.emit(SIGNAL("filePathChanged(QString)"), file) def __init__(self, parent=None, vectors="", rasters="", encodings=[]): QDialog.__init__(self, parent) self.contentsWidget = QListWidget() self.setWindowIcon(QIcon(":icon")) self.contentsWidget.setViewMode(QListView.IconMode) self.contentsWidget.setIconSize(QSize(76, 66)) self.contentsWidget.setMovement(QListView.Static) self.contentsWidget.setMaximumWidth(106) self.contentsWidget.setMinimumWidth(106) self.contentsWidget.setMinimumHeight(220) self.contentsWidget.setSpacing(12) self.__filePath = "" self.__encoding = "System" self.__type = 0 self.pagesWidget = QStackedWidget() vectorPage = self.VectorPage(self, vectors, encodings) self.pagesWidget.addWidget(vectorPage) rasterPage = self.RasterPage(self, rasters) self.pagesWidget.addWidget(rasterPage) buttons = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel, Qt.Horizontal, self) self.connect(buttons, SIGNAL("accepted()"), self.accept) self.connect(buttons, SIGNAL("rejected()"), self.reject) self.connect(vectorPage, SIGNAL("filePathChanged(QString)"), self.setFilePath) self.connect(vectorPage, SIGNAL("encodingChanged(QString)"), self.setEncoding) self.connect(rasterPage, SIGNAL("filePathChanged(QString)"), self.setFilePath) self.createIcons() self.contentsWidget.setCurrentRow(0) horizontalLayout = QHBoxLayout() horizontalLayout.addWidget(self.contentsWidget) horizontalLayout.addWidget(self.pagesWidget, 1) mainLayout = QVBoxLayout() mainLayout.addLayout(horizontalLayout) mainLayout.addStretch(1) mainLayout.addSpacing(12) mainLayout.addWidget(buttons) self.setLayout(mainLayout) self.setWindowTitle("manageR - Import Layer") def createIcons(self): vectorButton = QListWidgetItem(self.contentsWidget) vectorButton.setIcon(QIcon(":custom-vector.svg")) vectorButton.setText("Vector Layer") vectorButton.setTextAlignment(Qt.AlignHCenter) vectorButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) rasterButton = QListWidgetItem(self.contentsWidget) rasterButton.setIcon(QIcon(":custom-raster.svg")) rasterButton.setText("Raster Layer") rasterButton.setTextAlignment(Qt.AlignHCenter) rasterButton.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) self.connect(self.contentsWidget, SIGNAL("currentItemChanged(QListWidgetItem*, QListWidgetItem*)"), self.changePage) def changePage(self, current, previous): if not current: current = previous self.pagesWidget.setCurrentIndex(self.contentsWidget.row(current)) def filePath(self): return self.__filePath def setFilePath(self, filePath): self.__filePath = filePath def encoding(self): return self.__encoding def setEncoding(self, encoding): self.__encoding = encoding def layerType(self): return self.__type def setLayerType(self, type): self.__type = type def accept(self): self.__type = self.pagesWidget.currentIndex() QDialog.accept(self)
class SideBar( QWidget ): """ Sidebar with a widget area which is hidden or shown. On by clicking any tab, off by clicking the current tab. """ North = 0 East = 1 South = 2 West = 3 def __init__( self, orientation = 2, parent = None ): QWidget.__init__( self, parent ) self.__tabBar = QTabBar() self.__tabBar.setDrawBase( True ) self.__tabBar.setShape( QTabBar.RoundedNorth ) self.__tabBar.setFocusPolicy( Qt.NoFocus ) self.__tabBar.setUsesScrollButtons( True ) self.__tabBar.setElideMode( 1 ) self.__stackedWidget = QStackedWidget( self ) self.__stackedWidget.setContentsMargins( 0, 0, 0, 0 ) self.barLayout = QBoxLayout( QBoxLayout.LeftToRight ) self.barLayout.setMargin( 0 ) self.layout = QBoxLayout( QBoxLayout.TopToBottom ) self.layout.setMargin( 0 ) self.layout.setSpacing( 0 ) self.barLayout.addWidget( self.__tabBar ) self.layout.addLayout( self.barLayout ) self.layout.addWidget( self.__stackedWidget ) self.setLayout( self.layout ) self.__minimized = False self.__minSize = 0 self.__maxSize = 0 self.__bigSize = QSize() self.splitter = None self.__tabBar.installEventFilter( self ) self.__orientation = orientation self.setOrientation( orientation ) self.__tabBar.currentChanged.connect( self.__stackedWidget.setCurrentIndex ) return def setSplitter( self, splitter ): """ Set the splitter managing the sidebar """ self.splitter = splitter return def __getIndex( self ): " Provides the widget index in splitters " if self.__orientation == SideBar.West: return 0 if self.__orientation == SideBar.East: return 2 if self.__orientation == SideBar.South: return 1 return 0 def __getWidget( self ): " Provides a reference to the widget " return self.splitter.widget( self.__getIndex() ) def shrink( self ): """ Shrink the sidebar """ if self.__minimized: return self.__minimized = True self.__bigSize = self.size() if self.__orientation in [ SideBar.North, SideBar.South ]: self.__minSize = self.minimumHeight() self.__maxSize = self.maximumHeight() else: self.__minSize = self.minimumWidth() self.__maxSize = self.maximumWidth() self.__stackedWidget.hide() sizes = self.splitter.sizes() selfIndex = self.__getIndex() if self.__orientation in [ SideBar.North, SideBar.South ]: newHeight = self.__tabBar.minimumSizeHint().height() self.setFixedHeight( newHeight ) diff = sizes[ selfIndex ] - newHeight sizes[ selfIndex ] = newHeight else: newWidth = self.__tabBar.minimumSizeHint().width() self.setFixedWidth( newWidth ) diff = sizes[ selfIndex ] - newWidth sizes[ selfIndex ] = newWidth if selfIndex == 0: sizes[ 1 ] += diff else: sizes[ selfIndex - 1 ] += diff self.splitter.setSizes( sizes ) return def expand( self ): """ Expand the sidebar """ if not self.__minimized: return self.__minimized = False self.__stackedWidget.show() self.resize( self.__bigSize ) sizes = self.splitter.sizes() selfIndex = self.__getIndex() if self.__orientation in [ SideBar.North, SideBar.South ]: self.setMinimumHeight( self.__minSize ) self.setMaximumHeight( self.__maxSize ) diff = self.__bigSize.height() - sizes[ selfIndex ] sizes[ selfIndex ] = self.__bigSize.height() else: self.setMinimumWidth( self.__minSize ) self.setMaximumWidth( self.__maxSize ) diff = self.__bigSize.width() - sizes[ selfIndex ] sizes[ selfIndex ] = self.__bigSize.width() if selfIndex == 0: sizes[ 1 ] -= diff else: sizes[ selfIndex - 1 ] -= diff self.splitter.setSizes( sizes ) return def isMinimized( self ): """ Provides the minimized state """ return self.__minimized def eventFilter( self, obj, evt ): """ Handle click events for the tabbar """ if obj == self.__tabBar: if evt.type() == QEvent.MouseButtonPress: pos = evt.pos() index = self.__tabBar.count() - 1 while index >= 0: if self.__tabBar.tabRect( index ).contains( pos ): break index -= 1 if index == self.__tabBar.currentIndex(): if self.isMinimized(): self.expand() else: self.shrink() return True elif self.isMinimized(): if self.isTabEnabled( index ): self.expand() return QWidget.eventFilter( self, obj, evt ) def addTab( self, widget, iconOrLabel, label = None ): """ Add a tab to the sidebar """ if label: self.__tabBar.addTab( iconOrLabel, label ) else: self.__tabBar.addTab( iconOrLabel ) self.__stackedWidget.addWidget( widget ) return def insertTab( self, index, widget, iconOrLabel, label = None ): """ Insert a tab into the sidebar """ if label: self.__tabBar.insertTab( index, iconOrLabel, label ) else: self.__tabBar.insertTab( index, iconOrLabel ) self.__stackedWidget.insertWidget( index, widget ) return def removeTab( self, index ): """ Remove a tab """ self.__stackedWidget.removeWidget( self.__stackedWidget.widget( index ) ) self.__tabBar.removeTab( index ) return def clear( self ): """ Remove all tabs """ while self.count() > 0: self.removeTab( 0 ) return def prevTab( self ): """ Show the previous tab """ index = self.currentIndex() - 1 if index < 0: index = self.count() - 1 self.setCurrentIndex( index ) self.currentWidget().setFocus() return def nextTab( self ): """ Show the next tab """ index = self.currentIndex() + 1 if index >= self.count(): index = 0 self.setCurrentIndex( index ) self.currentWidget().setFocus() return def count( self ): """ Provides the number of tabs """ return self.__tabBar.count() def currentIndex( self ): """ Provides the index of the current tab """ return self.__stackedWidget.currentIndex() def setCurrentIndex( self, index ): """ Switch to the certain tab """ if index >= self.currentIndex(): return self.__tabBar.setCurrentIndex( index ) self.__stackedWidget.setCurrentIndex(index) if self.isMinimized(): self.expand() return def currentWidget( self ): """ Provide a reference to the current widget """ return self.__stackedWidget.currentWidget() def setCurrentWidget( self, widget ): """ Set the current widget """ self.__stackedWidget.setCurrentWidget( widget ) self.__tabBar.setCurrentIndex( self.__stackedWidget.currentIndex() ) if self.isMinimized(): self.expand() return def indexOf( self, widget ): """ Provides the index of the given widget """ return self.__stackedWidget.indexOf( widget ) def isTabEnabled( self, index ): """ Check if the tab is enabled """ return self.__tabBar.isTabEnabled( index ) def setTabEnabled( self, index, enabled ): """ Set the enabled state of the tab """ self.__tabBar.setTabEnabled( index, enabled ) return def orientation( self ): """ Provides the orientation of the sidebar """ return self.__orientation def setOrientation( self, orient ): """ Set the orientation of the sidebar """ if orient == SideBar.North: self.__tabBar.setShape( QTabBar.RoundedNorth ) self.barLayout.setDirection( QBoxLayout.LeftToRight ) self.layout.setDirection( QBoxLayout.TopToBottom ) self.layout.setAlignment( self.barLayout, Qt.AlignLeft ) elif orient == SideBar.East: self.__tabBar.setShape( QTabBar.RoundedEast ) self.barLayout.setDirection( QBoxLayout.TopToBottom ) self.layout.setDirection( QBoxLayout.RightToLeft ) self.layout.setAlignment( self.barLayout, Qt.AlignTop ) elif orient == SideBar.South: self.__tabBar.setShape( QTabBar.RoundedSouth ) self.barLayout.setDirection( QBoxLayout.LeftToRight ) self.layout.setDirection( QBoxLayout.BottomToTop ) self.layout.setAlignment( self.barLayout, Qt.AlignLeft ) else: # default orient = SideBar.West self.__tabBar.setShape( QTabBar.RoundedWest ) self.barLayout.setDirection( QBoxLayout.TopToBottom ) self.layout.setDirection( QBoxLayout.LeftToRight ) self.layout.setAlignment( self.barLayout, Qt.AlignTop ) self.__orientation = orient return def tabIcon( self, index ): """ Provide the icon of the tab """ return self.__tabBar.tabIcon( index ) def setTabIcon( self, index, icon ): """ Set the icon of the tab """ self.__tabBar.setTabIcon( index, icon ) return def tabText( self, index ): """ Provide the text of the tab """ return self.__tabBar.tabText( index ) def setTabText( self, index, text ): """ Set the text of the tab """ self.__tabBar.setTabText( index, text ) return def tabToolTip( self, index ): """ Provide the tooltip text of the tab """ return self.__tabBar.tabToolTip( index ) def setTabToolTip( self, index, tip ): """ Set the tooltip text of the tab """ self.__tabBar.setTabToolTip( index, tip ) return def tabWhatsThis( self, index ): """ Provide the WhatsThis text of the tab """ return self.__tabBar.tabWhatsThis( index ) def setTabWhatsThis( self, index, text ): """ Set the WhatsThis text for the tab """ self.__tabBar.setTabWhatsThis( index, text ) return def widget( self, index ): """ Provides the reference to the widget (QWidget) """ return self.__stackedWidget.widget( index )
class MainWindow(QMainWindow): def __init__(self, app): QMainWindow.__init__(self) self.options = self.parseOptions() if self.options.debug: level = DEBUG elif self.options.verbose: level = INFO else: level = ERROR setupStdoutLog(level) self.app = app self.async_response = AsyncReponse() self.pages = [] self.client = QtClient(self) self.setup() self.createWidgets() def _addPage(self, page): page.page_index = len(self.pages) self.pages.append(page) self.stacked.addWidget(page.widget) def createWidgets(self): self.stacked = QStackedWidget(self) self.game_list = GameList(self) self.create_game = CreateGame(self) self.setup_game = SetupGame(self) self.awale = Awale(self) self.mille_bornes = MilleBornes(self) self._addPage(self.game_list) self._addPage(self.create_game) self._addPage(self.setup_game) self._addPage(self.awale) self._addPage(self.mille_bornes) self.setCentralWidget(self.stacked) def parseOptions(self): parser = OptionParser(usage="%prog [options]") parser.add_option("--name", help='Player name (default: %s)' % DEFAULT_PLAYER_NAME, type="str", default=DEFAULT_PLAYER_NAME) parser.add_option("--host", help='Host name or IP (default: %s)' % DEFAULT_HOST, type="str", default=DEFAULT_HOST) parser.add_option("--port", help='Server TCP port (default: %s)' % DEFAULT_PORT, type="int", default=DEFAULT_PORT) parser.add_option("-v", "--verbose", help="Verbose mode", action="store_true", default=False) parser.add_option("--debug", help="Debug mode (don't call any service at startup)", action="store_true", default=False) parser.add_option("--create", metavar="GAME_TYPE", help="Create directly a game of type GAME_TYPE", type="str") parser.add_option("--join", metavar="GAME_ID", help="Join directly the game GAME_ID", type="int") options, arguments = parser.parse_args() if options.debug: options.verbose = True if arguments: parser.print_help() exit(1) return options def connectClient(self): self.client.connect(self.options.host, self.options.port) name = unicode(self.options.name) self.client.createPlayer(name) self.gotoGameListPage() def setup(self): self.app.setQuitOnLastWindowClosed(True) self.setWindowTitle(tr('Player %s') % self.options.name) def setActivePage(self, new_page): old_index = self.stacked.currentIndex() old_page = self.pages[old_index] old_page.exitPage() self.stacked.setCurrentIndex(new_page.page_index) new_page.enterPage() def gotoGameListPage(self): self.game_list.refresh() self.setActivePage(self.game_list) def gotoCreateGamePage(self): self.setActivePage(self.create_game) def gotoSetupGamePage(self, game): self.setup_game.init(game['id'], game['type']) self.setActivePage(self.setup_game) def gotoAwalePage(self, game_id): self.awale.init(game_id) self.setActivePage(self.awale) def gotoMilleBornesPage(self, game_id): self.mille_bornes.init(game_id) self.setActivePage(self.mille_bornes) def closeEvent(self, event): self.quit() def quit(self): self.client.quit() def infoPopup(self, text, title=None): if not title: title = tr("Information") QMessageBox.information(self, title, text) def errorPopup(self, text, title=None): if not title: title = tr("Error") QMessageBox.warning(self, title, text) def exception(self, err, title=None): text = exceptionAsUnicode(err) self.errorPopup(text, title) def main(self): create = self.options.create game_id = self.options.join if create: game = self.client.command(u'game_create', self.client.player_id, unicode(create), u'create') self.gotoSetupGamePage(game) elif game_id: game = self.client.command(u'game_info', [game_id])[0] self.client.command(u'game_join', game_id, self.client.player_id) self.gotoSetupGamePage(game) self.show()
class Declaration(QDialog, ui_declaration.Ui_Declaration): def __init__(self, parent, noi): super(Declaration, self).__init__(parent) self.setupUi(self) self.setStyleSheet(OfSs.declaration_page_style) self.noidec = noi self.parent = parent self.scenario = parent.scenario self.pages_widget = QStackedWidget(self) self.connect(self.pages_widget, SIGNAL("currentChanged(int)"), self.current_page_changed) self.connect(self.contents_widget, SIGNAL("currentRowChanged(int)"), self.pages_widget.setCurrentIndex) self.scrollArea.setWidget(self.pages_widget) self.connect(self.next_btn, SIGNAL('clicked()'), self.next_page) self.connect(self.prev_btn, SIGNAL('clicked()'), self.prev_page) self.pages = [ Page01(self), Page02(self), Page03(self), Page04(self), Page05(self), Page06(self), Page07(self), PageIsf(self) ] for widget in self.pages: self.add_page(widget) self.set_current_index(0) self.current_page_changed(0) def current_page_changed(self, index): nb = self.pages_widget.count() - 1 self.prev_btn.setEnabled(True) self.next_btn.setEnabled(True) if index == nb: self.next_btn.setEnabled(False) if index == 0: self.prev_btn.setEnabled(False) def next_page(self): idx = self.pages_widget.currentIndex() self.set_current_index(idx + 1) def prev_page(self): idx = self.pages_widget.currentIndex() self.set_current_index(idx - 1) def get_current_index(self): """Return current page index""" return self.contents_widget.currentRow() def set_current_index(self, index): """Set current page index""" self.contents_widget.setCurrentRow(index) self.pages_widget.setCurrentIndex(index) def accept(self): for page in self.pages: for key in page.__dict__: widget = getattr(page, key) if isinstance(widget, QSpinBox): var = str(widget.objectName()) val = widget.value() page.updateFoyer(var, val) elif isinstance(widget, QCheckBox): var = str(widget.objectName()) val = 1 * (widget.checkState() >= 1) page.updateFoyer(var, val) QDialog.accept(self) def add_page(self, widget): self.pages_widget.addWidget(widget) item = QListWidgetItem(self.contents_widget) item.setText(widget.get_name()) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)