本文整理汇总了Python中PyQt4.QtGui.QStackedLayout.addWidget方法的典型用法代码示例。如果您正苦于以下问题:Python QStackedLayout.addWidget方法的具体用法?Python QStackedLayout.addWidget怎么用?Python QStackedLayout.addWidget使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtGui.QStackedLayout
的用法示例。
在下文中一共展示了QStackedLayout.addWidget方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ComboEditor
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class ComboEditor(QWidget):
def __init__(self, original=False):
super(ComboEditor, self).__init__()
self.__original = original
vbox = QVBoxLayout(self)
vbox.setContentsMargins(0, 0, 0, 0)
self.bar = ActionBar()
self.connect(self.bar, SIGNAL("changeCurrent(PyQt_PyObject)"),
self.set_current)
vbox.addWidget(self.bar)
self.stacked = QStackedLayout()
vbox.addLayout(self.stacked)
def currentWidget(self):
return self.stacked.currentWidget()
def add_editor(self, neditable):
"""Add Editor Widget to the UI area."""
if neditable.editor:
self.stacked.addWidget(neditable.editor)
self.bar.add_item(neditable.display_name, neditable)
# Editor Signals
self.connect(neditable.editor, SIGNAL("cursorPositionChanged()"),
self._update_cursor_position)
# Connect file system signals only in the original
if self.__original:
pass
def set_current(self, neditable):
self.stacked.setCurrentWidget(neditable.editor)
self._update_cursor_position(ignore_sender=True)
neditable.editor.setFocus()
def widget(self, index):
return self.stacked.widget(index)
def count(self):
"""Return the number of editors opened."""
return self.stacked.count()
def _update_cursor_position(self, ignore_sender=False):
obj = self.sender()
editor = self.stacked.currentWidget()
# Check if it's current to avoid signals from other splits.
if ignore_sender or editor == obj:
line = editor.textCursor().blockNumber() + 1
col = editor.textCursor().columnNumber()
self.bar.update_line_col(line, col)
示例2: ComboTabs
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class ComboTabs(QWidget):
def __init__(self):
super(ComboTabs, self).__init__()
vbox = QVBoxLayout(self)
vbox.setContentsMargins(0, 0, 0, 0)
self.bar = ActionBar()
vbox.addWidget(self.bar)
self.stacked = QStackedLayout()
self.editable = neditable.NEditable('')
self.editor_widget = editor.create_editor(self.editable)
self.stacked.addWidget(self.editor_widget)
vbox.addLayout(self.stacked)
def currentWidget(self):
return self.editor_widget
示例3: CSVImportDialog
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class CSVImportDialog(QDialog):
def __init__(self, parent=None, **kwargs):
super(CSVImportDialog, self).__init__(parent, **kwargs)
self.setLayout(QVBoxLayout())
self._options = None
self._path = None
self.__update_pending = False
self._optionswidget = CSVOptionsWidget()
self._optionswidget.format_changed.connect(self._invalidate_preview)
self._stack = QStackedLayout()
self._stack.setContentsMargins(0, 0, 0, 0)
prev_box = QGroupBox("Preview")
prev_box.setLayout(self._stack)
self._preview = QTableView(tabKeyNavigation=False)
self._preview_error = QLabel()
self._stack.addWidget(self._preview)
self._stack.addWidget(self._preview_error)
buttons = QDialogButtonBox(
orientation=Qt.Horizontal,
standardButtons=(QDialogButtonBox.Ok | QDialogButtonBox.Cancel |
QDialogButtonBox.Reset)
)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
def on_clicked(button):
if buttons.buttonRole(button) == QDialogButtonBox.ResetRole:
self.reset()
buttons.clicked.connect(on_clicked)
self.layout().addWidget(self._optionswidget)
self.layout().addWidget(prev_box)
self.layout().addWidget(buttons)
def set_options(self, options):
self._options = options
self._optionswidget.set_dialect(options.dialect)
self._optionswidget.set_header_format(options.header_format)
self._optionswidget.set_missing_values(options.missing_values or "")
self._invalidate_preview()
def options(self):
missing_values = self._optionswidget.missing_values()
return CSV(self._optionswidget.dialect(),
header_format=self._optionswidget.header_format(),
missing_values=missing_values)
def set_path(self, path):
"""Set the preview path."""
if self._path != path:
self._path = path
self._invalidate_preview()
def path(self):
"""Return the preview path"""
return self._path
def reset(self):
"""Reset the options to their default values."""
self.set_options(self._options)
def _invalidate_preview(self):
if not self.__update_pending:
self.__update_pending = True
QApplication.postEvent(self, QEvent(QEvent.User))
def customEvent(self, event):
if self.__update_pending:
self.__update_pending = False
self._update_preview()
def _update_preview(self):
if not self._path:
return
head = itertools.islice(open(self._path, "rU"), 20)
head = StringIO("".join(head))
try:
data = load_csv(head, **self.options()._asdict())
except csv.Error as err:
self._preview_error.setText(
"Cannot load data preview:\n {!s}".format(err)
)
self._stack.setCurrentWidget(self._preview_error)
except (Orange.data.io.CSVFormatError,
Orange.data.io.VariableDefinitionError) as err:
self._preview_error.setText(
"Data formating error:\n {!s}".format(err)
)
self._stack.setCurrentWidget(self._preview_error)
except Exception as err:
self._preview_error.setText(
"Cannot load data preview:\n {!s}".format(err)
)
self._stack.setCurrentWidget(self._preview_error)
#.........这里部分代码省略.........
示例4: _MainContainer
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class _MainContainer(QWidget):
###############################################################################
# MainContainer SIGNALS
###############################################################################
"""
beforeFileSaved(QString)
fileSaved(QString)
currentTabChanged(QString)
locateFunction(QString, QString, bool) [functionName, filePath, isVariable]
--------openProject(QString)
openPreferences()
---------dontOpenStartPage()
-------navigateCode(bool, int)
----------addBackItemNavigation()
----------updateLocator(QString)
---------updateFileMetadata()
findOcurrences(QString)
--------cursorPositionChange(int, int) #row, col
fileOpened(QString)
newFileOpened(QString)
--------recentTabsModified(QStringList)
---------migrationAnalyzed()
allTabClosed()
"""
###############################################################################
def __init__(self, parent=None):
super(_MainContainer, self).__init__(parent)
self._parent = parent
self.stack = QStackedLayout(self)
self.splitter = dynamic_splitter.DynamicSplitter()
self.combo_area = combo_editor.ComboEditor(original=True)
#self.tabs = tab_widget.TabWidget(self)
self.setAcceptDrops(True)
self.splitter.addWidget(self.combo_area)
self.stack.addWidget(self.splitter)
self.current_split = self.combo_area
#documentation browser
self.docPage = None
#Code Navigation
self._locator = locator.Locator()
self.__codeBack = []
self.__codeForward = []
self.__bookmarksFile = ''
self.__bookmarksPos = -1
self.__breakpointsFile = ''
self.__breakpointsPos = -1
self.__operations = {
0: self._navigate_code_jumps,
1: self._navigate_bookmarks,
2: self._navigate_breakpoints}
self.connect(self, SIGNAL("locateFunction(QString, QString, bool)"),
self.locate_function)
#self.connect(self.tabs, SIGNAL("currentChanged(int)"),
#self._current_tab_changed)
#self.connect(self.tabs, SIGNAL("splitTab(QTabWidget, int, bool)"),
#self._split_this_tab)
#self.connect(self.tabs, SIGNAL("reopenTab(QString)"),
#self.open_file)
#self.connect(self.tabs, SIGNAL("syntaxChanged(QWidget, QString)"),
#self._specify_syntax)
#self.connect(self.tabs, SIGNAL("allTabsClosed()"),
#self._main_without_tabs)
##reload file
#self.connect(self.tabs, SIGNAL("reloadFile(QWidget)"),
#self.reload_file)
##for Save on Close operation
#self.connect(self.tabs, SIGNAL("saveActualEditor()"),
#self.save_file)
##Navigate Code
#self.connect(self.tabs, SIGNAL("navigateCode(bool, int)"),
#self.navigate_code_history)
## Refresh recent tabs
#self.connect(self.tabs, SIGNAL("recentTabsModified(QStringList)"),
#self._recent_files_changed)
IDE.register_service('main_container', self)
#Register signals connections
connections = (
{'target': 'menu_file',
'signal_name': 'openFile(QString)',
'slot': self.open_file},
{'target': 'explorer_container',
'signal_name': 'goToDefinition(int)',
'slot': self.editor_go_to_line},
{'target': 'explorer_container',
'signal_name': 'pep8Activated(bool)',
'slot': self.reset_pep8_warnings},
{'target': 'explorer_container',
'signal_name': 'lintActivated(bool)',
'slot': self.reset_lint_warnings},
)
IDE.register_signals('main_container', connections)
#.........这里部分代码省略.........
示例5: EkdConfigBox
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class EkdConfigBox(QDialog) :
"""
EkdConfigBox permet à l'utilisateur de configurer EkdConfig
"""
def __init__(self, w=550, h=480, titre=u"Configuration de Ekd", parent=None):
super(EkdConfigBox, self).__init__(parent)
self.resize(w,h)
self.w = w
self.h = h
self.setWindowTitle(titre)
self.layout = QVBoxLayout(self)
## Menu contient l'ensemble des sections à paramétrer
self.menu = QListWidget(self)
self.layout.addWidget(self.menu)
## Pour chaque section à paramétrer, on utilise un Stack d'objets
self.leftpart = QStackedLayout()
self.leftpart.setSizeConstraint(QLayout.SetNoConstraint)
self.layout.addLayout(self.leftpart)
## propWidget contient l'ensemble des objets propriété de toutes les section
## (il est nécessaire de les stocker pour être capable de les faire interagir)
self.propWidget=[]
wid = 0
## On crée les différentes parties de configuration qui ne sont pas inclues dans le tableau SECTION_MASK de EkdConfig
for section in EkdConfig.SECTIONS :
if not section in EkdConfig.SECTION_MASK :
self.menu.addItem(EkdConfig.SECTIONS[section])
allprops = EkdConfig.getAllProperties(EkdConfig.getConfigSection(section))
scroll = QScrollArea()
frame = QFrame()
frame.setMinimumSize(self.w-50, self.h/2) # Ajouté le 10/12/2009 Pour que la partie réglage prenne toute la place dispo.
frame.setMaximumSize(self.w, self.h)
linelayout = QGridLayout(frame)
linelayout.setSizeConstraint(QLayout.SetMinAndMaxSize)
row = 0
## Insertion des propriété de la section en fonction de son type
allkeys = allprops.keys()
found = False
for prop in allkeys :
if not prop in EkdConfig.PROPERTIES_MASK :
if prop in EkdConfig.PATH_PROPERTIES :
self.propWidget.append( EkdPathPropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], section=section) )
linelayout.addWidget(self.propWidget[wid].label, row, 0)
linelayout.addWidget(self.propWidget[wid].widget, row, 1)
wid += 1
found = True
row += 1
for prop in allkeys :
if not prop in EkdConfig.PROPERTIES_MASK :
if prop in EkdConfig.STYLE_PROPERTIES :
self.propWidget.append( EkdStylePropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], EkdConfig.STYLE_PROPERTIES[prop], section=section ) )
linelayout.addWidget(self.propWidget[wid].label, row, 0)
linelayout.addWidget(self.propWidget[wid].widget, row, 1)
wid += 1
found = True
row += 1
for prop in allkeys :
if not prop in EkdConfig.PROPERTIES_MASK :
if prop in EkdConfig.CODEC_PROPERTIES :
self.propWidget.append( EkdCodecPropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], EkdConfig.CODEC_PROPERTIES[prop], section=section ) )
linelayout.addWidget(self.propWidget[wid].label, row, 0)
linelayout.addWidget(self.propWidget[wid].widget, row, 1)
wid += 1
found = True
row += 1
for prop in allkeys :
if not prop in EkdConfig.PROPERTIES_MASK :
if prop in EkdConfig.BOOLEAN_PROPERTIES :
self.propWidget.append( EkdBoolPropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], section=section) )
linelayout.addWidget(self.propWidget[wid].widget, row, 0, 1, 2)
wid += 1
found = True
row += 1
for prop in allkeys :
if not prop in EkdConfig.PROPERTIES_MASK :
if prop in EkdConfig.NUM_PROPERTIES :
self.propWidget.append( EkdNumPropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], section=section) )
linelayout.addWidget(self.propWidget[wid].label, row, 0)
linelayout.addWidget(self.propWidget[wid].widget, row, 1)
wid += 1
found = True
row += 1
for prop in allkeys :
if not prop in EkdConfig.PROPERTIES_MASK :
if prop in EkdConfig.TIME_PROPERTIES :
self.propWidget.append( EkdTimePropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], section=section) )
linelayout.addWidget(self.propWidget[wid].label, row, 0)
linelayout.addWidget(self.propWidget[wid].widget, row, 1)
wid += 1
found = True
row += 1
for prop in allkeys :
if not prop in EkdConfig.PROPERTIES_MASK :
if prop in EkdConfig.COLOR_PROPERTIES :
self.propWidget.append( EkdColorPropertie(prop, EkdConfig.PROPERTIES[prop], allprops[prop], section=section) )
linelayout.addWidget(self.propWidget[wid].label, row, 0)
linelayout.addWidget(self.propWidget[wid].widget, row, 1)
#.........这里部分代码省略.........
示例6: _MainContainer
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
#.........这里部分代码省略.........
self.selector = main_selector.MainSelector(self)
self._opening_dialog = False
self.add_widget(self.selector)
if settings.SHOW_START_PAGE:
self.show_start_page()
self.connect(self.selector, SIGNAL("changeCurrent(int)"),
self._change_current_stack)
self.connect(self.selector, SIGNAL("removeWidget(int)"),
self._remove_item_from_stack)
self.connect(self.selector, SIGNAL("ready()"),
self._selector_ready)
self.connect(self.selector, SIGNAL("animationCompleted()"),
self._selector_animation_completed)
self.connect(self, SIGNAL("closeDialog(PyQt_PyObject)"),
self.remove_widget)
def install(self):
ide = IDE.get_service('ide')
ide.place_me_on("main_container", self, "central", top=True)
self.combo_area = combo_editor.ComboEditor(original=True)
self.connect(self.combo_area, SIGNAL("allFilesClosed()"),
self._files_closed)
self.splitter.add_widget(self.combo_area)
self.add_widget(self.splitter)
self.current_widget = self.combo_area
ui_tools.install_shortcuts(self, actions.ACTIONS, ide)
def add_status_bar(self, status):
self._vbox.addWidget(status)
@property
def combo_header_size(self):
return self.combo_area.bar.height()
def add_widget(self, widget):
self.stack.addWidget(widget)
def remove_widget(self, widget):
self.stack.removeWidget(widget)
def _close_dialog(self, widget):
self.emit(SIGNAL("closeDialog(PyQt_PyObject)"), widget)
self.disconnect(widget, SIGNAL("finished(int)"),
lambda: self._close_dialog(widget))
def show_dialog(self, widget):
self._opening_dialog = True
self.connect(widget, SIGNAL("finished(int)"),
lambda: self._close_dialog(widget))
self.setVisible(True)
self.stack.addWidget(widget)
self.show_selector()
def show_selector(self):
if self.selector != self.stack.currentWidget():
temp_dir = os.path.join(QDir.tempPath(), "ninja-ide")
if not os.path.exists(temp_dir):
os.mkdir(temp_dir)
collected_data = []
current = self.stack.currentIndex()
for index in range(self.stack.count()):
示例7: CMainWindow
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class CMainWindow(QFrame):
def __init__(self):
QMainWindow.__init__(self)
layout = QGridLayout(self)
layout.setMargin(2)
btnFiles = QPushButton(u'Файлы', self)
btnVideo = QPushButton(u'Видео', self)
btnPlay = QPushButton(u'Play/Pause', self)
btnStop = QPushButton(u'Stop', self)
btnMute = QPushButton(u'Mute', self)
btnMute.setCheckable(True)
btnMainMenu = QPushButton(u'Main', self)
self.sldVolume = QSlider(Qt.Vertical, self)
self.sldPosition = QSlider(Qt.Horizontal, self)
self.layMain = QStackedLayout()
btnFiles.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
btnVideo.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
btnPlay.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
btnStop.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
btnMute.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
btnMainMenu.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.sldVolume.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
self.sldPosition.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
layout.addWidget(btnFiles, 0, 0)
layout.addWidget(btnVideo, 0, 1)
layout.addWidget(btnPlay, 0, 3)
layout.addWidget(btnStop, 0, 4)
layout.addWidget(btnMute, 0, 5)
layout.addWidget(btnMainMenu, 2, 5)
layout.addWidget(self.sldVolume, 1, 5)
layout.addWidget(self.sldPosition, 2, 0, 1, 5)
layout.addLayout(self.layMain, 1, 0, 1, 5)
fileBrowser = CFileBrowser(self)
self.videoWidget = QWidget(self)
self.exitMenu = CExitMenu(self)
self.mplayer = MPlayerControl(self, self.videoWidget)
fileBrowser.chosen.connect(self.startPlay)
btnFiles.clicked.connect(lambda: self.selectMode(0))
btnVideo.clicked.connect(lambda: self.selectMode(1))
btnMainMenu.clicked.connect(lambda: self.selectMode(2))
self.sldPosition.valueChanged.connect(self.mplayer.seek)
self.sldVolume.valueChanged.connect(self.mplayer.setvol)
btnMute.clicked.connect(lambda: self.mplayer.mute(btnMute.isChecked()))
btnPlay.clicked.connect(self.mplayer.play)
btnStop.clicked.connect(self.mplayer.stop)
self.sldVolume.setValue(QtGui.qApp.settings['volume'])
self.mplayer.percent_position.connect(self.on_mplayer_position)
self.layMain.addWidget(fileBrowser)
self.layMain.addWidget(self.videoWidget)
self.layMain.addWidget(self.exitMenu)
@pyqtSlot(int)
def on_mplayer_position(self, pos):
self.sldPosition.blockSignals(True)
self.sldPosition.setValue(pos)
self.sldPosition.blockSignals(False)
@pyqtSlot(int)
def selectMode(self, mode):
self.layMain.setCurrentIndex(mode)
@pyqtSlot(str)
def startPlay(self, path):
self.selectMode(1)
self.mplayer.play(path)
def closeEvent(self, event):
self.mplayer.quit()
QFrame.closeEvent(self, event)
示例8: ProjectTreeColumn
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class ProjectTreeColumn(QDialog):
def __init__(self, parent=None):
super(ProjectTreeColumn, self).__init__(parent,
Qt.WindowStaysOnTopHint)
vbox = QVBoxLayout(self)
vbox.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
vbox.setContentsMargins(0, 0, 0, 0)
self._buttons = []
self._combo_project = QComboBox()
self._combo_project.setMinimumHeight(30)
self._combo_project.setContextMenuPolicy(Qt.CustomContextMenu)
vbox.addWidget(self._combo_project)
self._projects_area = QStackedLayout()
logger.debug("This is the projects area")
logger.debug(self._projects_area)
vbox.addLayout(self._projects_area)
self.projects = []
self.connect(self._combo_project, SIGNAL("currentIndexChanged(int)"),
self._change_current_project)
self.connect(self._combo_project, SIGNAL(
"customContextMenuRequested(const QPoint &)"),
self.context_menu_for_root)
connections = (
{'target': 'main_container',
'signal_name': 'addToProject(QString)',
'slot': self._add_file_to_project},
{'target': 'main_container',
'signal_name': 'showFileInExplorer(QString)',
'slot': self._show_file_in_explorer},
)
IDE.register_service('projects_explorer', self)
IDE.register_signals('projects_explorer', connections)
ExplorerContainer.register_tab(translations.TR_TAB_PROJECTS, self)
#FIXME: Should have a ninja settings object that stores tree state
#FIXME: Or bettter, application data object
#TODO: check this:
#self.connect(ide, SIGNAL("goingDown()"),
#self.tree_projects.shutdown)
#def close_project_signal():
#self.emit(SIGNAL("updateLocator()"))
def install_tab(self):
ide = IDE.get_service('ide')
ui_tools.install_shortcuts(self, actions.PROJECTS_TREE_ACTIONS, ide)
self.connect(ide, SIGNAL("goingDown()"), self.close)
def load_session_projects(self, projects):
for project in projects:
if os.path.exists(project):
self._open_project_folder(project)
def open_project_folder(self, folderName=None):
if settings.WORKSPACE:
directory = settings.WORKSPACE
else:
directory = os.path.expanduser("~")
if folderName is None:
folderName = QFileDialog.getExistingDirectory(
self, translations.TR_OPEN_PROJECT_DIRECTORY, directory)
logger.debug("Choosing Foldername")
if folderName:
logger.debug("Opening %s" % folderName)
self._open_project_folder(folderName)
def _open_project_folder(self, folderName):
ninjaide = IDE.get_service("ide")
project = NProject(folderName)
qfsm = ninjaide.filesystem.open_project(project)
if qfsm:
self.add_project(project)
self.emit(SIGNAL("updateLocator()"))
self.save_recent_projects(folderName)
main_container = IDE.get_service('main_container')
if main_container:
main_container.show_editor_area()
def _add_file_to_project(self, path):
"""Add the file for 'path' in the project the user choose here."""
if self._active_project:
pathProject = [self._active_project.project]
addToProject = add_to_project.AddToProject(pathProject, self)
addToProject.exec_()
if not addToProject.pathSelected:
return
main_container = IDE.get_service('main_container')
if not main_container:
return
editorWidget = main_container.get_current_editor()
if not editorWidget.file_path:
name = QInputDialog.getText(None,
translations.TR_ADD_FILE_TO_PROJECT,
#.........这里部分代码省略.........
示例9: MusicPreviewWidget
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class MusicPreviewWidget(QWidget):
def __init__(self, parent=None):
super(MusicPreviewWidget, self).__init__(parent)
self._lastbuildtime = 10.0
self._running = None
self._current = None
self._chooserLabel = QLabel()
self._chooser = QComboBox(self, activated=self.selectDocument)
self._log = log.Log()
self._view = popplerview.View()
self._progress = widgets.progressbar.TimedProgressBar()
self._stack = QStackedLayout()
self._top = QWidget()
layout = QVBoxLayout()
self.setLayout(layout)
layout.addWidget(self._top)
layout.addLayout(self._stack)
layout.addWidget(self._progress)
top = QHBoxLayout()
top.setContentsMargins(0, 0, 0, 0)
top.setSpacing(2)
self._top.setLayout(top)
top.addWidget(self._chooserLabel)
top.addWidget(self._chooser)
top.addStretch(1)
self._stack.addWidget(self._log)
self._stack.addWidget(self._view)
self._top.hide()
app.aboutToQuit.connect(self.cleanup)
app.translateUI(self)
def translateUI(self):
self._chooserLabel.setText(_("Document:"))
def preview(self, text, title=None):
"""Runs LilyPond on the given text and shows the resulting PDF."""
j = self._running = MusicPreviewJob(text, title)
j.done.connect(self._done)
self._log.clear()
self._log.connectJob(j)
j.start()
self._progress.start(self._lastbuildtime)
def _done(self, success):
self._progress.stop(False)
pdfs = self._running.resultfiles()
self.setDocuments(pdfs)
if not pdfs:
self._stack.setCurrentWidget(self._log)
return
self._lastbuildtime = self._running.elapsed_time()
self._stack.setCurrentWidget(self._view)
if self._current:
self._current.cleanup()
self._current = self._running # keep the tempdir
self._running = None
def setDocuments(self, pdfs):
"""Loads the given PDF path names in the UI."""
self._documents = [popplertools.Document(name) for name in pdfs]
self._chooser.clear()
self._chooser.addItems([d.name() for d in self._documents])
self._top.setVisible(len(self._documents) > 1)
if pdfs:
self._chooser.setCurrentIndex(0)
self.selectDocument(0)
else:
self._view.clear()
def selectDocument(self, index):
doc = self._documents[index].document()
if doc:
self._view.load(doc)
def cleanup(self):
if self._running:
self._running.abort()
self._running.cleanup()
self._running = None
if self._current:
self._current.cleanup()
self._current = None
self._stack.setCurrentWidget(self._log)
self._top.hide()
self._view.clear()
def print_(self):
"""Prints the currently displayed document."""
if self._documents:
doc = self._documents[self._chooser.currentIndex()]
import popplerprint
popplerprint.printDocument(doc, self)
示例10: Preferences
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class Preferences(QDialog):
configuration = {}
weight = 0
def __init__(self, parent=None):
super(Preferences, self).__init__(parent, Qt.Dialog)
self.setWindowTitle(translations.TR_PREFERENCES_TITLE)
self.setMinimumSize(QSize(800, 600))
self.setMaximumSize(QSize(0, 0))
vbox = QVBoxLayout(self)
hbox = QHBoxLayout()
vbox.setContentsMargins(0, 0, 5, 5)
hbox.setContentsMargins(0, 0, 0, 0)
self.tree = QTreeWidget()
self.tree.header().setHidden(True)
self.tree.setSelectionMode(QTreeWidget.SingleSelection)
self.tree.setAnimated(True)
self.tree.header().setHorizontalScrollMode(
QAbstractItemView.ScrollPerPixel)
self.tree.header().setResizeMode(0, QHeaderView.ResizeToContents)
self.tree.header().setStretchLastSection(False)
self.tree.setFixedWidth(200)
self.stacked = QStackedLayout()
hbox.addWidget(self.tree)
hbox.addLayout(self.stacked)
vbox.addLayout(hbox)
hbox_footer = QHBoxLayout()
self._btnSave = QPushButton(translations.TR_SAVE)
self._btnCancel = QPushButton(translations.TR_CANCEL)
hbox_footer.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
hbox_footer.addWidget(self._btnCancel)
hbox_footer.addWidget(self._btnSave)
vbox.addLayout(hbox_footer)
self.connect(self.tree, SIGNAL("itemSelectionChanged()"),
self._change_current)
self.connect(self._btnCancel, SIGNAL("clicked()"), self.close)
self.connect(self._btnSave, SIGNAL("clicked()"),
self._save_preferences)
self.load_ui()
self.tree.setCurrentItem(self.tree.topLevelItem(0))
def _save_preferences(self):
self.emit(SIGNAL("savePreferences()"))
self.close()
def load_ui(self):
sections = sorted(list(Preferences.configuration.keys()),
key=lambda item: Preferences.configuration[item]['weight'])
for section in sections:
text = Preferences.configuration[section]['text']
Widget = Preferences.configuration[section]['widget']
widget = Widget(self)
area = QScrollArea()
area.setWidgetResizable(True)
area.setWidget(widget)
index = self.stacked.addWidget(area)
item = QTreeWidgetItem([text])
item.setData(0, Qt.UserRole, index)
self.tree.addTopLevelItem(item)
#Sort Item Children
subcontent = Preferences.configuration[section].get(
'subsections', {})
subsections = sorted(list(subcontent.keys()),
key=lambda item: subcontent[item]['weight'])
for sub in subsections:
text = subcontent[sub]['text']
Widget = subcontent[sub]['widget']
widget = Widget(self)
area = QScrollArea()
area.setWidgetResizable(True)
area.setWidget(widget)
index = self.stacked.addWidget(area)
subitem = QTreeWidgetItem([text])
subitem.setData(0, Qt.UserRole, index)
item.addChild(subitem)
self.tree.expandAll()
def _change_current(self):
item = self.tree.currentItem()
index = item.data(0, Qt.UserRole)
self.stacked.setCurrentIndex(index)
@classmethod
def register_configuration(cls, section, widget, text, weight=None,
subsection=None):
if weight is None:
Preferences.weight += 1
weight = Preferences.weight
if not subsection:
Preferences.configuration[section] = {'widget': widget,
'weight': weight, 'text': text}
else:
config = Preferences.configuration.get(section, {})
#.........这里部分代码省略.........
示例11: InstallWizard
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class InstallWizard(QDialog):
def __init__(self, config, network, storage, app):
QDialog.__init__(self)
self.app = app
self.config = config
self.network = network
self.storage = storage
self.setMinimumSize(575, 400)
self.setMaximumSize(575, 400)
self.setWindowTitle('Electrum-VCN' + ' - ' + _('Install Wizard'))
self.connect(self, QtCore.SIGNAL('accept'), self.accept)
self.stack = QStackedLayout()
self.setLayout(self.stack)
def set_layout(self, layout):
w = QWidget()
w.setLayout(layout)
self.stack.addWidget(w)
self.stack.setCurrentWidget(w)
self.show()
def restore_or_create(self):
vbox = QVBoxLayout()
main_label = QLabel(_("Electrum-VCN could not find an existing wallet."))
vbox.addWidget(main_label)
grid = QGridLayout()
grid.setSpacing(5)
gb1 = QGroupBox(_("What do you want to do?"))
vbox.addWidget(gb1)
vbox1 = QVBoxLayout()
gb1.setLayout(vbox1)
b1 = QRadioButton(gb1)
b1.setText(_("Create new wallet"))
b1.setChecked(True)
b2 = QRadioButton(gb1)
b2.setText(_("Restore a wallet or import keys"))
group1 = QButtonGroup()
group1.addButton(b1)
group1.addButton(b2)
vbox1.addWidget(b1)
vbox1.addWidget(b2)
gb2 = QGroupBox(_("Wallet type:"))
vbox.addWidget(gb2)
vbox2 = QVBoxLayout()
gb2.setLayout(vbox2)
group2 = QButtonGroup()
self.wallet_types = [
('standard', _("Standard wallet")),
('twofactor', _("Wallet with two-factor authentication")),
('multisig', _("Multi-signature wallet")),
('hardware', _("Hardware wallet")),
]
for i, (wtype, name) in enumerate(self.wallet_types):
if not filter(lambda x: x[0] == wtype, electrum.wallet.wallet_types):
continue
button = QRadioButton(gb2)
button.setText(name)
vbox2.addWidget(button)
group2.addButton(button)
group2.setId(button, i)
if i == 0:
button.setChecked(True)
vbox.addStretch(1)
self.set_layout(vbox)
vbox.addLayout(Buttons(CancelButton(self), OkButton(self, _('Next'))))
self.show()
self.raise_()
if not self.exec_():
return None, None
action = 'create' if b1.isChecked() else 'restore'
wallet_type = self.wallet_types[group2.checkedId()][0]
return action, wallet_type
def verify_seed(self, seed, sid, func=None):
r = self.enter_seed_dialog(MSG_VERIFY_SEED, sid, func)
if not r:
return
if prepare_seed(r) != prepare_seed(seed):
QMessageBox.warning(None, _('Error'), _('Incorrect seed'), _('OK'))
return False
else:
return True
def get_seed_text(self, seed_e):
#.........这里部分代码省略.........
示例12: CenterView
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class CenterView(QWidget):
img_correct = '<img src="%s" height="22" width="22">' % utils.resource_path("correct.svg")
img_incorrect = '<img src="%s" height="22" width="22">' % utils.resource_path("incorrect.svg")
img_unanswered = '<img src="%s" height="22" width="22">' % utils.resource_path("unanswered.svg")
def __init__(self, parent=None):
super(CenterView, self).__init__(parent)
layout = QVBoxLayout()
self.setLayout(layout)
self.center = QStackedLayout()
self.camview = widgets.CamView((640, 480), self, draw_logo=True)
self.label_up = QLabel()
self.label_down = QLabel()
self.center.addWidget(self.camview)
layout.addLayout(self.center)
layout.addWidget(self.label_up)
layout.addWidget(self.label_down)
self.adjustSize()
self.setFixedSize(self.sizeHint())
def update_status(self, score, model=None, seq_num=None, survey_mode=False):
parts = []
if score is not None:
if not survey_mode:
parts.append(CenterView.img_correct)
if score.correct is not None:
parts.append(str(score.correct) + " ")
else:
parts.append("--- ")
parts.append(CenterView.img_incorrect)
if score.incorrect is not None:
parts.append(str(score.incorrect) + " ")
else:
parts.append("--- ")
parts.append(CenterView.img_unanswered)
if score.blank is not None:
parts.append(str(score.blank) + " ")
else:
parts.append("--- ")
if score.score is not None and score.max_score is not None:
parts.append(_("Score: {0:.2f} / {1:.2f}").format(score.score, score.max_score))
parts.append(" ")
else:
parts.append(_("[Survey mode on]"))
parts.append(" ")
if model is not None:
parts.append(_("Model:") + " " + model + " ")
if seq_num is not None:
parts.append(_("Num.:") + " " + str(seq_num) + " ")
self.label_down.setText(('<span style="white-space: pre">' + " ".join(parts) + "</span>"))
def update_text_up(self, text):
self.label_up.setText(text)
def update_text_down(self, text):
self.label_down.setText(text)
def display_capture(self, ipl_image):
"""Displays a captured image in the window.
The image is in the OpenCV IPL format.
"""
self.camview.display_capture(ipl_image)
def display_wait_image(self):
"""Displays the default image instead of a camera capture."""
self.camview.display_wait_image()
def register_listener(self, key, listener):
"""Registers listeners for the center view.
Available listeners are:
- ('camview', 'mouse_pressed'): mouse pressed in the camview
area. The listener receives the coordinates (x, y) as a
tuple.
"""
if key[0] == "camview":
if key[1] == "mouse_pressed":
self.camview.register_mouse_pressed_listener(listener)
else:
assert False, "Undefined listener key: {0}".format(key)
else:
assert False, "Undefined listener key: {0}".format(key)
示例13: LoginView
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class LoginView(QDialog,View):
_mainLayout_ = None
#We put all widgets in container widgets,
#If we add all of them to layouts by themselves we get Bus error
#when doing mainLayout.addLayout()
_usernameWidget_ = None
_passWidget_ = None
_rememberWidget_ = None
_buttonsWidget_ = None
_logoLabel_ = None
_usernameLabel_ = None
_passwordLabel_ = None
_usernameLineEdit_ = None
_passwordLineEdit_ = None
_rememberCheckbox_ = None
_registerButton_ = None
_loginButton_ = None
_myBloopSiteLink_ = None #QLabel
_movieWaiting_ = None #Gotta keep a refernce to the .GIF, otherwise it won't send signals to the QLabel
_controller_ = None
_menuBar_ = None
def __init__(self, parent=None):
'''
Initializes all components in the dialog.
Whoever uses this view, and its controller,
must letter bind the controller and the view
using view.setController(c)
The controller then will be able to access
all the view elements with the getters
defined in this dummy view class.
The controller can also connect to events
triggered by this dialog.
'''
QDialog.__init__(self)
View.__init__(self)
#self.createMenubar()
#set up the fields
self.setWindowTitle(i18n.LABEL_WINDOW_LOGIN_TITLE)
imagePath = os.path.join("i18n","images","us_en")
self.setWindowIcon(QIcon(os.path.join(imagePath,"bloop.png")))
#Blooploader Logo
pixmap = QPixmap(os.path.join('i18n','images','us_en','login_logo.png'))
assert(not pixmap.isNull())
self._logoLabel_ = QLabel()
self._logoLabel_.setPixmap(pixmap)
#login row
self._usernameLabel_ = QLabel(i18n.LABEL_USERNAME)
self._usernameLineEdit_ = QLineEdit()
self._usernameWidget_ = PairedWidget(self._usernameLabel_, self._usernameLineEdit_)
#password row
self._passwordLabel_ = QLabel(i18n.LABEL_PASSWORD)
self._passwordLineEdit_ = QLineEdit()
self._passwordLineEdit_.setEchoMode(QLineEdit.Password)
self._passWidget_ = PairedWidget(self._passwordLabel_, self._passwordLineEdit_)
#remember me row
self._rememberCheckbox_ = QCheckBox(i18n.LABEL_REMEMBER_ME)
self._rememberWidget_= QWidget()
rememberLayout = QHBoxLayout()
rememberLayout.addStretch()
rememberLayout.addWidget(self._rememberCheckbox_)
self._rememberWidget_.setLayout(rememberLayout)
#buttons
self._loginButton_ = QPushButton(i18n.LABEL_LOGIN)
self._buttonsWidget_ = QHBoxLayout()
self._buttonsWidget_.addStretch()
self._buttonsWidget_.addWidget(self._loginButton_)
#MyBloop.com Link at the end
self._myBloopSiteLink_ = QLabel('<a href="http://www.mybloop.com">www.mybloop.com</a>')
myBloopSiteLinkLayout = QHBoxLayout()
myBloopSiteLinkLayout.addStretch()
myBloopSiteLinkLayout.addWidget(self._myBloopSiteLink_)
myBloopSiteLinkLayout.addStretch()
#Stack em up vertically
self._mainLayout_ = QVBoxLayout()
self._mainLayout_.addStretch()
self._mainLayout_.addWidget(self._logoLabel_,0,Qt.AlignCenter)
self._mainLayout_.addWidget(self._usernameWidget_)
self._mainLayout_.addWidget(self._passWidget_)
self._mainLayout_.addWidget(self._rememberWidget_)
self._mainLayout_.addLayout(self._buttonsWidget_)
self._mainLayout_.addLayout(myBloopSiteLinkLayout)
self._mainLayout_.addStretch()
#Add another layout to show while we wait
#put all this on a QStackedLayout
self._passwordLineEdit_.setStyleSheet("border-style: outset; border-width: 1px; border-radius: 3px; border-color: gray; padding: 3px;")
#.........这里部分代码省略.........
示例14: ComboEditor
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class ComboEditor(QWidget):
def __init__(self, original=False):
super(ComboEditor, self).__init__()
self.__original = original
self._symbols_index = []
vbox = QVBoxLayout(self)
vbox.setContentsMargins(0, 0, 0, 0)
vbox.setSpacing(0)
self.bar = ActionBar()
vbox.addWidget(self.bar)
self.stacked = QStackedLayout()
vbox.addLayout(self.stacked)
self._main_container = IDE.get_service('main_container')
self.connect(self.bar, SIGNAL("changeCurrent(PyQt_PyObject)"),
self.set_current)
self.connect(self.bar, SIGNAL("runFile(QString)"),
self._run_file)
self.connect(self.bar, SIGNAL("addToProject(QString)"),
self._add_to_project)
self.connect(self.bar, SIGNAL("goToSymbol(int)"),
self._go_to_symbol)
self.connect(self.bar, SIGNAL("reopenTab(QString)"),
lambda path: self._main_container.open_file(path))
self.connect(self.bar, SIGNAL("recentTabsModified()"),
lambda: self._main_container.recent_files_changed())
self.connect(self.bar.code_navigator.btnPrevious, SIGNAL("clicked()"),
lambda: self._navigate_code(False))
self.connect(self.bar.code_navigator.btnNext, SIGNAL("clicked()"),
lambda: self._navigate_code(True))
def _navigate_code(self, val):
op = self.bar.code_navigator.operation
self._main_container.navigate_code_history(val, op)
def currentWidget(self):
return self.stacked.currentWidget()
def add_editor(self, neditable):
"""Add Editor Widget to the UI area."""
if neditable.editor:
self.stacked.addWidget(neditable.editor)
self.bar.add_item(neditable.display_name, neditable)
# Editor Signals
self.connect(neditable.editor, SIGNAL("cursorPositionChanged()"),
self._update_cursor_position)
self.connect(neditable.editor, SIGNAL("currentLineChanged(int)"),
self._set_current_symbol)
self.connect(neditable, SIGNAL("checkersUpdated(PyQt_PyObject)"),
self._show_notification_icon)
self.connect(neditable, SIGNAL("fileSaved(PyQt_PyObject)"),
self._update_symbols)
# Connect file system signals only in the original
self.connect(neditable, SIGNAL("fileClosing(PyQt_PyObject)"),
self._close_file)
if self.__original:
self.connect(neditable,
SIGNAL("neverSavedFileClosing(PyQt_PyObject)"),
self._ask_for_save)
# Load Symbols
self._load_symbols(neditable)
def show_combo_file(self):
self.bar.combo.showPopup()
def close_current_file(self):
self.bar.about_to_close_file()
def _close_file(self, neditable):
index = self.bar.close_file(neditable)
layoutItem = self.stacked.takeAt(index)
neditable.editor.completer.cc.unload_module()
self._add_to_last_opened(neditable.file_path)
layoutItem.widget().deleteLater()
def _add_to_last_opened(self, path):
if path not in settings.LAST_OPENED_FILES:
settings.LAST_OPENED_FILES.append(path)
if len(settings.LAST_OPENED_FILES) > settings.MAX_REMEMBER_TABS:
self.__lastOpened = self.__lastOpened[1:]
self.emit(SIGNAL("recentTabsModified()"))
def _ask_for_save(self, neditable):
val = QMessageBox.No
fileName = neditable.file_path
val = QMessageBox.question(
self, (self.tr('The file %s was not saved') %
fileName),
self.tr("Do you want to save before closing?"),
QMessageBox.Yes | QMessageBox.No |
QMessageBox.Cancel)
if val == QMessageBox.No:
neditable.nfile.close(force_close=True)
#.........这里部分代码省略.........
示例15: CodeCompletionWidget
# 需要导入模块: from PyQt4.QtGui import QStackedLayout [as 别名]
# 或者: from PyQt4.QtGui.QStackedLayout import addWidget [as 别名]
class CodeCompletionWidget(QFrame):
def __init__(self, editor):
super(CodeCompletionWidget, self).__init__(
None, Qt.FramelessWindowHint | Qt.ToolTip)
self._editor = editor
self._revision = 0
self._block = 0
self.stack_layout = QStackedLayout(self)
self.stack_layout.setContentsMargins(0, 0, 0, 0)
self.stack_layout.setSpacing(0)
self.completion_list = QListWidget()
self.completion_list.setMinimumHeight(200)
self.completion_list.setAlternatingRowColors(True)
self._list_index = self.stack_layout.addWidget(self.completion_list)
self._icons = {'a': resources.IMAGES['attribute'],
'f': resources.IMAGES['function'],
'c': resources.IMAGES['class'],
'm': resources.IMAGES['module']}
self.cc = code_completion.CodeCompletion()
self._completion_results = {}
self._prefix = u''
self.setVisible(False)
self.source = ''
self._key_operations = {
Qt.Key_Up: self._select_previous_row,
Qt.Key_Down: self._select_next_row,
Qt.Key_PageUp: (lambda: self._select_previous_row(6)),
Qt.Key_PageDown: (lambda: self._select_next_row(6)),
Qt.Key_Right: lambda: None,
Qt.Key_Left: lambda: None,
Qt.Key_Enter: self.pre_key_insert_completion,
Qt.Key_Return: self.pre_key_insert_completion,
Qt.Key_Tab: self.pre_key_insert_completion,
Qt.Key_Space: self.hide_completer,
Qt.Key_Escape: self.hide_completer,
Qt.Key_Backtab: self.hide_completer,
Qt.NoModifier: self.hide_completer,
Qt.ShiftModifier: self.hide_completer,
}
self.desktop = QApplication.instance().desktop()
self.connect(self.completion_list,
SIGNAL("itemClicked(QListWidgetItem*)"),
self.pre_key_insert_completion)
self.connect(self._editor.document(),
SIGNAL("cursorPositionChanged(QTextCursor)"),
self.update_metadata)
def _select_next_row(self, move=1):
new_row = self.completion_list.currentRow() + move
if new_row < self.completion_list.count():
self.completion_list.setCurrentRow(new_row)
else:
self.completion_list.setCurrentRow(0)
return True
def _select_previous_row(self, move=1):
new_row = self.completion_list.currentRow() - move
if new_row >= 0:
self.completion_list.setCurrentRow(new_row)
else:
self.completion_list.setCurrentRow(
self.completion_list.count() - move)
return True
def update_metadata(self, cursor):
if settings.CODE_COMPLETION:
if self._editor.document().revision() != self._revision and \
cursor.block().blockNumber() != self._block:
source = self._editor.get_text()
source = source.encode(self._editor.encoding)
self.cc.analyze_file(self._editor.ID, source)
self._revision = self._editor.document().revision()
self._block = cursor.block().blockNumber()
def insert_completion(self, insert, type_=ord('a')):
if insert != self._prefix:
closing = ''
if type_ in (ord('f'), ord('c')):
closing = '()'
extra = len(self._prefix) - len(insert)
insertion = '%s%s' % (insert[extra:], closing)
self._editor.textCursor().insertText(insertion)
self.hide_completer()
def _get_geometry(self):
cr = self._editor.cursorRect()
desktop_geometry = self.desktop.availableGeometry(self._editor)
point = self._editor.mapToGlobal(cr.topLeft())
cr.moveTopLeft(point)
#Check new position according desktop geometry
width = (self.completion_list.sizeHintForColumn(0) +
self.completion_list.verticalScrollBar().sizeHint().width() + 10)
height = 200
orientation = (point.y() + height) < desktop_geometry.height()
if orientation:
#.........这里部分代码省略.........