本文整理汇总了Python中PyQt4.QtCore.QSignalMapper.setMapping方法的典型用法代码示例。如果您正苦于以下问题:Python QSignalMapper.setMapping方法的具体用法?Python QSignalMapper.setMapping怎么用?Python QSignalMapper.setMapping使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtCore.QSignalMapper
的用法示例。
在下文中一共展示了QSignalMapper.setMapping方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: contextMenuEvent
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
def contextMenuEvent(self, event):
menu = QtGui.QMenu()
last_pos = event.pos()
cursor = self.cursorForPosition(last_pos)
pos = cursor.positionInBlock()
line = cursor.blockNumber()
keywords = self.words_at_pos(line, pos)
if len(keywords) > 0:
keyword_mapper = QSignalMapper(self)
actions = []
for keyword in keywords:
action_text = "Copy \"%s\"" % keyword[0].meaning
actions.append(QtGui.QAction(action_text, None))
# We can only send strings with the signal mapper, so pickle our data.
data = pickle.dumps(keyword[0])
data = QtCore.QString.fromAscii(data)
self.connect(actions[-1], QtCore.SIGNAL("triggered()"), keyword_mapper, QtCore.SLOT("map()"))
keyword_mapper.setMapping(actions[-1], data)
self.connect(keyword_mapper, QtCore.SIGNAL("mapped(QString)"), self.copy_keyword)
menu.addActions(actions)
menu.addSeparator()
default_menu = self.createStandardContextMenu()
menu.addActions(default_menu.actions())
menu.exec_(event.globalPos())
示例2: LEDDialog
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
class LEDDialog(QDialog):
rowwidth = 20
def __init__(self, strip, parent=None):
super(LEDDialog,self).__init__(parent)
self.strip = strip
self.buttons = []
layout = QVBoxLayout()
btnlayout = QGridLayout()
self.btnmapper = QSignalMapper()
for i in xrange(int(self.strip.config['nleds'])):
p = QPushButton()
p.setFixedWidth(40)
p.setFlat(True)
p.setAutoFillBackground(True)
self.btnmapper.setMapping( p, i)
p.clicked.connect( self.btnmapper.map)
self.buttons += [[p,QColor()]]
btnlayout.addWidget(p, i/self.rowwidth, i%self.rowwidth)
self.btnmapper.mapped['int'].connect(self.chooseColor)
layout.addLayout(btnlayout)
ctrllayout = QHBoxLayout()
p = QPushButton("Refresh")
p.clicked.connect(self.refresh)
ctrllayout.addWidget(p)
p = QPushButton("Set")
p.clicked.connect(self.set)
ctrllayout.addWidget(p)
p = QPushButton("Close")
p.clicked.connect(self.close)
ctrllayout.addWidget(p)
layout.addLayout(ctrllayout)
self.setLayout( layout)
self.refresh()
def refresh(self):
tmp = self.strip.state()
for i in xrange(len(self.buttons)):
c = QColor(int(tmp[i*3+0]),int(tmp[i*3+1]),int(tmp[i*3+2]))
pal = self.buttons[i][0].palette()
pal.setBrush( QPalette.Button, QColor(c.red(),c.green(),c.blue()))
self.buttons[i][0].setPalette(pal)
self.buttons[i][1] = c
def set(self):
leds = []
for b,c in self.buttons:
leds += [ c.red(), c.green(), c.blue() ]
self.strip.setState(leds)
time.sleep(0.1)
self.refresh()
def chooseColor(self, i):
if not i < len(self.buttons): return
initial = self.buttons[i][1]
c = QColorDialog.getColor(initial,self)
if initial == c: return
pal = self.buttons[i][0].palette()
pal.setBrush( QPalette.Button, QColor(c.red(),c.green(),c.blue()))
self.buttons[i][0].setPalette(pal)
self.buttons[i][1] = c
示例3: ProviderToolBar
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
class ProviderToolBar(QToolBar):
'''
Widget to display the vehicles/objects status and position
'''
triggered = pyqtSignal(str)
def __init__(self, parent=None):
super(ProviderToolBar, self).__init__(parent)
self.signalMapper = QSignalMapper(self)
self.setMovable(True)
self.setFloatable(True)
self.upToDate = False
self.actions = []
self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
self.signalMapper.mapped[str].connect(self.triggered)
def createAction(self, provider):
icon = QIcon(':/plugins/PosiView/ledgreen.png')
icon.addFile(':/plugins/PosiView/ledgrey.png', QSize(), QIcon.Disabled, QIcon.Off)
action = QAction(icon, provider.name, None)
button = QToolButton()
button.setDefaultAction(action)
action.setEnabled(False)
provider.deviceConnected.connect(action.setEnabled)
provider.deviceDisconnected.connect(action.setDisabled)
self.signalMapper.setMapping(action, provider.name)
action.triggered.connect(self.signalMapper.map)
self.addAction(action)
self.actions.append(action)
示例4: __init__
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
def __init__(self, parent, tester):
"""Construct a new dockwindow following the tester """
self.tester = tester
QtGui.QDockWidget.__init__(self, tester.testname, parent)
self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
if not self.widget():
self.setWidget(QtGui.QWidget(self))
vl = QtGui.QVBoxLayout(self.widget())
#self.widget().setLayout(vl)
panel = QtGui.QFrame(self)
vl.addWidget(panel)
self.login = QtGui.QLineEdit(self)
self.login.textEdited.connect(self.check_logpass)
self.password = QtGui.QLineEdit(self)
self.password.setEchoMode(QtGui.QLineEdit.Password)
self.password.textEdited.connect(self.check_logpass)
self.tests = []
fl = QtGui.QFormLayout(panel)
fl.addRow('&Login:',self.login)
fl.addRow('&Password:',self.password)
panel.setLayout(fl)
panel = QtGui.QFrame(self)
panel.setFrameShadow(QtGui.QFrame.Sunken)
panel.setFrameShape(QtGui.QFrame.Panel)
vl.addWidget(panel)
vl2 = QtGui.QVBoxLayout(panel)
signalmapper = QSignalMapper(self)
signalmapper.mapped[int].connect(self.test)
for i,test in enumerate(self.tester.tests):
btn = QtGui.QPushButton("Test {}: {}".format(i+1,test.name),panel)
btn.setStyleSheet(self.btn_default_stylesheet)
btn.setEnabled(False)
vl2.addWidget(btn)
self.tests.append(btn)
signalmapper.setMapping(btn,i)
btn.clicked.connect(signalmapper.map)
panel.setLayout(vl2)
self.text = QtGui.QLabel("Enter your Coursera login and assignments password and push one of the test buttons above to run the test and submit the results to Coursera.")
self.text.setWordWrap(True)
vl.addWidget(self.text)
self.text.setFrameShadow(QtGui.QFrame.Sunken)
self.text.setFrameShape(QtGui.QFrame.Panel)
self.text.setMargin(5)
#vl.setStretch(2,1)
vl.addStretch(1)
示例5: setup_file_locs
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
def setup_file_locs(self):
# Because the default margins are ugly as h*ck.
self.ui.tabLocs.layout().setContentsMargins(0, 0, 0, 0)
# Map our buttons to functions that retrieve the necessary data.
cfg_mapper = QSignalMapper(self)
for i, item in enumerate(FILE_LOCATIONS):
self.connect(self.ui.__dict__[item[BTN]], QtCore.SIGNAL("clicked()"), cfg_mapper, QtCore.SLOT("map()"))
cfg_mapper.setMapping(self.ui.__dict__[item[BTN]], i)
self.connect(cfg_mapper, QtCore.SIGNAL("mapped(int)"), self.__get_cfg_item)
# Load in all our info from the config file.
for item in FILE_LOCATIONS:
self.ui.__dict__[item[TEXT]].setText(common.editor_config.get_pref(item[CFG]))
示例6: setupSelectMapper
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
class SelectMapper:
def setupSelectMapper(self, selectMapper, selectAllButton=None):
"""selectMapper should include keys 'button'(QPushButton) and 'widget'(QWidget)
"""
self._select = None
self.selectMapper = selectMapper
self.selectAllButton = selectAllButton
self.signalMapper = QSignalMapper(self)
for key, value in self.selectMapper.iteritems():
# config signal mapper
value['button'].clicked.connect(self.signalMapper.map)
self.signalMapper.setMapping(value['button'], key)
# connect signal mapper to slot 'select'
QObject.connect(self.signalMapper, SIGNAL("mapped(QString)"), self.select)
if selectAllButton:
selectAllButton.clicked.connect(self.selectAll)
def select(self, select):
select = unicode(select)
self.selectMapper[select]['button'].setChecked(True)
if self._select == select: return
if self._select:
self.selectMapper[self._select]['button'].setChecked(False)
self.selectMapper[self._select]['widget'].hide()
else:
if self.selectAllButton:
self.selectAllButton.setChecked(False)
for key, value in self.selectMapper.iteritems():
value['widget'].hide()
self.selectMapper[select]['widget'].show()
self._select = select
def selectAll(self):
self.selectAllButton.setChecked(True)
if self._select == None: return
for key, value in self.selectMapper.iteritems():
value['button'].setChecked(False)
value['widget'].show()
self._select = None
示例7: __init__
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
def __init__(self, items, colCount, parent=None):
"""
Create Grid and setup QSignalMapper.
Connect each item's 'clicked' signal and use the sequence index
as map value which will be passed as argument when the Grid's
clicked signal is emitted.
items: sequence with widgets having a 'void clicked()' signal
colCount: column count for each row
parent: parent widget, default None
"""
super(Grid, self).__init__(parent)
# Create a grid layout.
layout = QGridLayout()
self.setLayout(layout)
# Create the signal mapper.
signalMapper = QSignalMapper(self)
for cnt, item in enumerate(items):
# Setup mapping for the item. In this case, the
# mapping is the sequence index of the item.
signalMapper.setMapping(item, cnt)
# Connect the item's 'clicked' signal to the signal
# mapper's 'map' slot.
# The 'map' slot will emit the 'mapped' signal
# when invoked and the mapping set previously will be
# passed as an argument to the slot/signal that is
# connected to the signal mapper's 'mapped' signal.
item.clicked.connect(signalMapper.map)
# Add the widget to the grid layout
layout.addWidget(item, cnt / colCount, cnt % colCount)
# Forward the signal mapper's 'mapped' signal via the Grid's
# 'clicked' signal. This will handle all widgets' 'clicked'
# ssignals.
signalMapper.mapped.connect(self.clicked)
示例8: ImportData
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
class ImportData(QWizard, Ui_frmImport):
def __init__(self,parent=None):
QWizard.__init__(self,parent)
self.setupUi(self)
self.curr_profile = current_profile()
#Connect signals
self.btnBrowseSource.clicked.connect(self.setSourceFile)
self.lstDestTables.itemClicked.connect(self.destSelectChanged)
self.btnSrcUp.clicked.connect(self.srcItemUp)
self.btnSrcDown.clicked.connect(self.srcItemDown)
self.btnSrcAll.clicked.connect(self.checkSrcItems)
self.btnSrcNone.clicked.connect(self.uncheckSrcItems)
self.btnDestUp.clicked.connect(self.targetItemUp)
self.btnDestDown.clicked.connect(self.targetItemDown)
self.lstSrcFields.currentRowChanged[int].connect(self.sourceRowChanged)
self.lstTargetFields.currentRowChanged[int].connect(self.destRowChanged)
self.lstTargetFields.currentRowChanged[int].connect(self._enable_disable_trans_tools)
self.chk_virtual.toggled.connect(self._on_load_virtual_columns)
#Data Reader
self.dataReader = None
#Init
self.registerFields()
#Geometry columns
self.geomcols = []
#Initialize value translators from definitions
self._init_translators()
#self._set_target_fields_stylesheet()
def _init_translators(self):
translator_menu = QMenu(self)
self._trans_widget_mgr = TranslatorWidgetManager(self)
self._trans_signal_mapper = QSignalMapper(self)
for trans_name, config in ValueTranslatorConfig.translators.iteritems():
trans_action = QAction( u'{}...'.format(trans_name),
translator_menu
)
self._trans_signal_mapper.setMapping(trans_action, trans_name)
trans_action.triggered.connect(self._trans_signal_mapper.map)
translator_menu.addAction(trans_action)
if len(translator_menu.actions()) == 0:
self.btn_add_translator.setEnabled(False)
else:
self.btn_add_translator.setMenu(translator_menu)
self._trans_signal_mapper.mapped[str].connect(self._load_translator_dialog)
self.btn_edit_translator.setEnabled(False)
self.btn_delete_translator.setEnabled(False)
self.btn_edit_translator.clicked.connect(self._on_edit_translator)
self.btn_delete_translator.clicked.connect(self._on_delete_translator)
def _load_translator_dialog(self, config_key):
"""
Load translator dialog.
"""
dest_column = self._selected_destination_column()
src_column = self._selected_source_column()
if dest_column:
#Check if there is an existing dialog in the manager
trans_dlg = self._trans_widget_mgr.translator_widget(dest_column)
if trans_dlg is None:
trans_config = ValueTranslatorConfig.translators.get(config_key, None)
#Safety precaution
if trans_config is None: return
try:
trans_dlg = trans_config.create(
self,
self._source_columns(),
self.targetTab,
dest_column,
src_column
)
except RuntimeError as re:
QMessageBox.critical(
self,
QApplication.translate(
'ImportData',
'Value Translator'
),
unicode(re)
)
#.........这里部分代码省略.........
示例9: TratadorInterface
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
class TratadorInterface(QMainWindow, Ui_InterfaceQt, Observer):
erro_vertice_existe = pyqtSignal()
erro_vertice_nao_existe = pyqtSignal(str)
def __init__(self):
Observer.__init__(self)
QMainWindow.__init__(self)
super(TratadorInterface, self).__init__(self)
self.setupUi(self)
self.erro_vertice_existe.connect(self.verticeExiste)
self.erro_vertice_nao_existe.connect(self.verticeNaoExiste)
self.eh_funcao.setEnabled(False)
self.funcao_edit.setEnabled(False)
self.grafo = None
self.signalMapper = QSignalMapper(self)
@pyqtSlot()
def on_adicionar_vertice_button_clicked(self):
if not self.grafo:
nome = str(self.nome_edit.text())
if nome == '':
QMessageBox(self).critical(self, 'ERRO', 'O Gravo deve ter um nome!', buttons=QMessageBox.Ok)
return
self.grafo = AlgoritmosGrafoNO(nome)
self.observe(self.grafo)
self.limparInferencias()
vertices = str(self.vertices_edit.text())
vertices = vertices.split(',')
if len(vertices) > 0:
self.signalMapper = QSignalMapper(self)
for vertice in vertices:
vertice = vertice.strip()
if vertice != '':
cont = self.tabela_adjacencia.rowCount()
item = QTableWidgetItem(vertice)
self.tabela_adjacencia.insertColumn(cont)
self.tabela_adjacencia.insertRow(cont)
self.tabela_adjacencia.setHorizontalHeaderItem(cont,item)
self.tabela_adjacencia.setVerticalHeaderItem(cont,item)
self.grafo.adicionarVertice(vertice)
for x in xrange(self.tabela_adjacencia.rowCount()):
comboV = QComboBox(self)
comboH = QComboBox(self)
comboV.addItems(['0','1'])
comboH.addItems(['0','1'])
comboV.setSizePolicy(QSizePolicy().Minimum, QSizePolicy().Minimum)
comboH.setSizePolicy(QSizePolicy().Minimum, QSizePolicy().Minimum)
self.tabela_adjacencia.setCellWidget(cont,x,comboH)
self.tabela_adjacencia.setCellWidget(x,cont,comboV)
for x in xrange(self.tabela_adjacencia.rowCount()):
for y in xrange(self.tabela_adjacencia.rowCount()):
item = self.tabela_adjacencia.cellWidget(x, y)
self.connect(item, SIGNAL('currentIndexChanged(int)'),self.signalMapper, SLOT('map()'))
self.signalMapper.setMapping(item, '{0};{1}'.format(x,y))
self.connect(self.signalMapper, SIGNAL('mapped(QString)'), self.valorAlterado)
self.tabela_adjacencia.resizeColumnsToContents()
self.tabela_adjacencia.resizeRowsToContents()
self.fecho_origem.addItems(vertices)
self.informacoes_vertice.addItems(vertices)
self.busca_destino.addItems(vertices)
self.busca_origem.addItems(vertices)
self.remover_vertice_combo.addItems(vertices)
self.ordem_resultado.setText(str(self.grafo.obterOrdem()))
self.gerar_arestas_button.setEnabled(True)
self.vertices_edit.clear()
@pyqtSlot()
def on_remover_vertice_button_clicked(self):
QMessageBox.critical(self, 'ERRO INTERNO', u'Ação não disponívl devido à um erro interno do QT', buttons=QMessageBox.Ok, defaultButton=QMessageBox.NoButton)
'''
vertice = self.remover_vertice_combo.currentText()
colunas = self.tabela_adjacencia.columnCount()
for x in xrange(colunas):
if vertice == str(self.tabela_adjacencia.horizontalHeaderItem(x).text()):
for y in xrange(self.tabela_adjacencia.columnCount()):
self.tabela_adjacencia.removeCellWidget(y,x)
self.tabela_adjacencia.removeColumn(x)
self.fecho_origem.removeItem(self.fecho_origem.findText(vertice))
self.informacoes_vertice.removeItem(self.informacoes_vertice.findText(vertice))
self.busca_destino.removeItem(self.busca_destino.findText(vertice))
self.busca_origem.removeItem(self.busca_origem.findText(vertice))
self.remover_vertice_combo.removeItem(self.remover_vertice_combo.findText(vertice))
self.ordem_resultado.setText(str(self.grafo.obterOrdem()))
break
'''
@pyqtSlot()
def on_gerar_arestas_button_clicked(self):
self.limparInferencias()
self.grafo.limpar()
n_linhas = self.tabela_adjacencia.rowCount()
n_colunas = self.tabela_adjacencia.columnCount()
for x in xrange(n_linhas):
#.........这里部分代码省略.........
示例10: main
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
def main(icon_spec):
app = QApplication(sys.argv)
main_window = QMainWindow()
def sigint_handler(*args):
main_window.close()
signal.signal(signal.SIGINT, sigint_handler)
# the timer enables triggering the sigint_handler
signal_timer = QTimer()
signal_timer.start(100)
signal_timer.timeout.connect(lambda: None)
tool_bar = QToolBar()
main_window.addToolBar(Qt.TopToolBarArea, tool_bar)
table_view = QTableView()
table_view.setSelectionBehavior(QAbstractItemView.SelectRows)
table_view.setSelectionMode(QAbstractItemView.SingleSelection)
table_view.setSortingEnabled(True)
main_window.setCentralWidget(table_view)
proxy_model = QSortFilterProxyModel()
proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
proxy_model.setFilterKeyColumn(1)
table_view.setModel(proxy_model)
proxy_model.layoutChanged.connect(table_view.resizeRowsToContents)
item_model = QStandardItemModel()
proxy_model.setSourceModel(item_model)
# get all icons and their available sizes
QIcon.setThemeName("gnome")
icons = []
all_sizes = set([])
for context, icon_names in icon_spec:
for icon_name in icon_names:
icon = QIcon.fromTheme(icon_name)
sizes = []
for size in icon.availableSizes():
size = (size.width(), size.height())
sizes.append(size)
all_sizes.add(size)
sizes.sort()
icons.append({
'context': context,
'icon_name': icon_name,
'icon': icon,
'sizes': sizes,
})
all_sizes = list(all_sizes)
all_sizes.sort()
# input field for filter
def filter_changed(value):
proxy_model.setFilterRegExp(value)
table_view.resizeRowsToContents()
filter_line_edit = QLineEdit()
filter_line_edit.setMaximumWidth(200)
filter_line_edit.setPlaceholderText('Filter name')
filter_line_edit.setToolTip('Filter name optionally using regular expressions (' + QKeySequence(QKeySequence.Find).toString() + ')')
filter_line_edit.textChanged.connect(filter_changed)
tool_bar.addWidget(filter_line_edit)
# actions to toggle visibility of available sizes/columns
def action_toggled(index):
column = 2 + index
table_view.setColumnHidden(column, not table_view.isColumnHidden(column))
table_view.resizeColumnsToContents()
table_view.resizeRowsToContents()
signal_mapper = QSignalMapper()
for i, size in enumerate(all_sizes):
action = QAction('%dx%d' % size, tool_bar)
action.setCheckable(True)
action.setChecked(True)
tool_bar.addAction(action)
action.toggled.connect(signal_mapper.map)
signal_mapper.setMapping(action, i)
# set tool tip and handle key sequence
tool_tip = 'Toggle visibility of column'
if i < 10:
digit = ('%d' % (i + 1))[-1]
tool_tip += ' (%s)' % QKeySequence('Ctrl+%s' % digit).toString()
action.setToolTip(tool_tip)
signal_mapper.mapped.connect(action_toggled)
# label columns
header_labels = ['context', 'name']
for width, height in all_sizes:
header_labels.append('%dx%d' % (width, height))
item_model.setColumnCount(len(header_labels))
item_model.setHorizontalHeaderLabels(header_labels)
# fill rows
item_model.setRowCount(len(icons))
for row, icon_data in enumerate(icons):
# context
item = QStandardItem(icon_data['context'])
item.setFlags(item.flags() ^ Qt.ItemIsEditable)
item_model.setItem(row, 0, item)
#.........这里部分代码省略.........
示例11: DocumentViewManager
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
#.........这里部分代码省略.........
else:
has_mdi_child = False
self._close_act.setEnabled(has_mdi_child)
self._close_all_act.setEnabled(has_mdi_child)
self._tile_act.setEnabled(has_mdi_child)
self._cascade_act.setEnabled(has_mdi_child)
self._previous_act.setEnabled(has_mdi_child)
self._next_act.setEnabled(has_mdi_child)
self._separator_act.setVisible(has_mdi_child)
def update_window_menu(self):
self._window_menu.clear()
self._window_menu.addAction(self._close_act)
self._window_menu.addAction(self._close_all_act)
self._window_menu.addSeparator()
self._window_menu.addAction(self._tile_act)
self._window_menu.addAction(self._cascade_act)
self._window_menu.addSeparator()
self._window_menu.addAction(self._next_act)
self._window_menu.addAction(self._previous_act)
self._window_menu.addAction(self._separator_act)
windows = self._mdi_area.subWindowList()
self._separator_act.setVisible(len(windows) != 0)
for i, window in enumerate(windows):
text = "%d. %s" % (i + 1, window.windowTitle())
win_action = self._window_menu.addAction(text)
win_action.setCheckable(True)
win_action.setChecked(window is self._mdi_area.activeSubWindow())
win_action.triggered.connect(self._viewer_mapper.map)
self._viewer_mapper.setMapping(win_action, window)
def load_viewer(self, document_widget, visible=True):
"""
Open a new instance of the viewer or activate an existing one if the
document had been previously loaded.
:param document_widget: Contains all the necessary information required
to load the specific document.
:type document_widget: DocumentWidget
:param visible: True to show the view manager after the viewer has
been loaded, otherwise it will be the responsibility of the caller to
enable visibility.
:type visible: bool
:returns: True if the document was successfully loaded, else False.
:rtype: bool
"""
doc_identifier = document_widget.file_identifier()
if doc_identifier in self._doc_viewers:
doc_sw = self._doc_viewers[doc_identifier]
self._mdi_area.setActiveSubWindow(doc_sw)
doc_sw.showNormal()
else:
doc_viewer = self._create_viewer(document_widget)
abs_doc_path = self.absolute_document_path(document_widget)
if not QFile.exists(abs_doc_path):
msg = QApplication.translate(
"DocumentViewManager",
示例12: Context
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
class Context(QDialog):
"""
Context dialog. Responsoble for viewing full thread.
There are a "bug" here - I have to duplicate some functions from main
module due to architecture fail. I will fix that, soon.
Parameters:
@auth - connector instance for communication with statusnet installation
@conversation_id - conversation id. Nuff said.
@settings - QTDenter settings
@self.version - QTDenter self.version
"""
def __init__(self, auth, conversation_id, settings, version, parent = None):
QDialog.__init__(self, parent)
self.ui = cg.Ui_Dialog()
self.ui.setupUi(self)
self.settings = settings
self.auth = auth
self.version = version
# Initialize signal mappers for buttons and lists for buttons pointers
self.context_buttons_mapper = QSignalMapper(self)
self.context_buttons_list = []
self.destroy_buttons_mapper = QSignalMapper(self)
self.destroy_buttons_list = []
self.redent_buttons_mapper = QSignalMapper(self)
self.redent_buttons_list = []
self.like_buttons_mapper = QSignalMapper(self)
self.like_buttons_list = []
self.dentid_buttons_mapper = QSignalMapper(self)
self.dentid_buttons_list = []
self.ui.context.setSortingEnabled(True)
self.ui.context.sortByColumn(2, Qt.DescendingOrder)
for column in range(2, 6):
self.ui.context.setColumnHidden(column, True)
self.ui.context.setColumnWidth(0, 65)
self.ui.context.itemActivated.connect(self.reply_to_dent)
conversation = self.auth.get_conversation(conversation_id)
self.list_handler = list_handler.List_Handler(self.callback)
self.list_item = list_item.list_item()
self.list_handler.add_data("conversation", conversation, self.settings["server"])
self.connect_buttons()
def connect_buttons(self):
print "Connecting buttons"
for item in self.context_buttons_list:
self.context_buttons_mapper.setMapping(item[0], item[1])
item[0].clicked.connect(self.context_buttons_mapper.map)
for item in self.destroy_buttons_list:
self.destroy_buttons_mapper.setMapping(item[0], item[1])
item[0].clicked.connect(self.destroy_buttons_mapper.map)
for item in self.redent_buttons_list:
self.redent_buttons_mapper.setMapping(item[0], item[1])
item[0].clicked.connect(self.redent_buttons_mapper.map)
for item in self.like_buttons_list:
self.like_buttons_mapper.setMapping(item[0], item[1])
item[0].clicked.connect(self.like_buttons_mapper.map)
for item in self.dentid_buttons_list:
self.dentid_buttons_mapper.setMapping(item[0], item[1])
item[0].clicked.connect(self.dentid_buttons_mapper.map)
self.destroy_buttons_mapper.mapped.connect(self.delete_dent)
self.redent_buttons_mapper.mapped.connect(self.redent_dent)
self.like_buttons_mapper.mapped.connect(self.like_dent)
self.dentid_buttons_mapper.mapped.connect(self.go_to_dent)
def callback(self, dent_type, data, server):
"""
List callback
"""
if dent_type == "end":
pass
else:
self.add_dent(data, dent_type)
def add_dent(self, data, dent_type):
"""
Add dent to list widget
"""
item_data = self.list_item.process_item(data, self.settings["last_dent_id"], self.settings["user"], self.settings["server"], dent_type)
item = item_data[0]
avatar_widget = item_data[1]
post_widget = item_data[2]
destroy_button = avatar_widget.findChild(QPushButton, "destroy_button_" + str(data["id"]))
dentid_button = post_widget.findChild(QPushButton, "dentid_button_" + str(data["id"]))
redent_button = post_widget.findChild(QPushButton, "redent_button_" + str(data["id"]))
like_button = post_widget.findChild(QPushButton, "like_button_" + str(data["id"]))
#.........这里部分代码省略.........
示例13: ToolBox
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
#.........这里部分代码省略.........
page.widget.hide()
page.widget.setParent(self)
self.__updatePositions()
self.__updateSelected()
self.updateGeometry()
def count(self):
"""
Return the number of widgets inserted in the toolbox.
"""
return len(self.__pages)
def widget(self, index):
"""
Return the widget at `index`.
"""
return self.__pages[index].widget
def createTabButton(self, widget, text, icon=None, toolTip=None):
"""
Create the tab button for `widget`.
"""
action = QAction(text, self)
action.setCheckable(True)
if icon:
action.setIcon(icon)
if toolTip:
action.setToolTip(toolTip)
self.__tabActionGroup.addAction(action)
self.__actionMapper.setMapping(action, action)
action.toggled.connect(self.__actionMapper.map)
button = ToolBoxTabButton(self, objectName="toolbox-tab-button")
button.setDefaultAction(action)
button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
button.setSizePolicy(QSizePolicy.Expanding,
QSizePolicy.Fixed)
if self.__tabIconSize.isValid():
button.setIconSize(self.__tabIconSize)
if self.__tabButtonHeight > 0:
button.setFixedHeight(self.__tabButtonHeight)
return button
def ensureWidgetVisible(self, child, xmargin=50, ymargin=50):
"""
Scroll the contents so child widget instance is visible inside
the viewport.
"""
self.__scrollArea.ensureWidgetVisible(child, xmargin, ymargin)
def sizeHint(self):
hint = self.__contentsLayout.sizeHint()
if self.count():
# Compute max width of hidden widgets also.
scroll = self.__scrollArea
scroll_w = scroll.verticalScrollBar().sizeHint().width()
frame_w = self.frameWidth() * 2 + scroll.frameWidth() * 2
示例14: TrackingWindow
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
#.........这里部分代码省略.........
def closeEvent(self, event):
self.saveConfig()
if not self.ensure_save_data("Exiting whith unsaved data",
"The last modifications you made were not saved."
" Are you sure you want to exit?"):
event.ignore()
return
QMainWindow.closeEvent(self, event)
#sys.exit(0)
def loadConfig(self):
params = parameters.instance
self.ui.action_Show_vector.setChecked(params.show_vectors)
self.ui.linkViews.setChecked(params.link_views)
self.ui.action_Show_template.setChecked(parameters.instance.show_template)
self.ui.actionShow_id.setChecked(parameters.instance.show_id)
self.ui.action_Estimate_position.setChecked(parameters.instance.estimate)
self.updateRecentFiles()
params.recentProjectsChange.connect(self.updateRecentFiles)
def updateRecentFiles(self):
for a in self._recent_projects_act:
self._projects_mapper.removeMappings(a)
del self._recent_projects_act[:]
menu = self._recent_projects_menu
menu.clear()
recent_projects = parameters.instance.recent_projects
for i, p in enumerate(recent_projects):
act = QAction(self)
act.setText("&{0:d} {1}".format(i + 1, p))
self._recent_projects_act.append(act)
act.triggered.connect(self._projects_mapper.map)
self._projects_mapper.setMapping(act, i)
menu.addAction(act)
def saveConfig(self):
parameters.instance.save()
def check_for_data(self):
if self._project is None:
QMessageBox.critical(self, "No project loaded",
"You have to load a project before performing this operation")
return False
return True
def loadRecentProject(self, i):
if self.ensure_save_data("Leaving unsaved data",
"The last modifications you made were not saved."
" Are you sure you want to change project?"):
self.loadProject(parameters.instance.recent_projects[i])
@pyqtSignature("")
def on_action_Open_project_triggered(self):
if self.ensure_save_data("Leaving unsaved data",
"The last modifications you made were not saved."
" Are you sure you want to change project?"):
dir_ = QFileDialog.getExistingDirectory(self, "Select a project directory",
parameters.instance._last_dir)
if dir_:
self.loadProject(dir_)
def loadProject(self, dir_):
dir_ = path(dir_)
project = Project(dir_)
if project.valid:
示例15: CollectionAggregator
# 需要导入模块: from PyQt4.QtCore import QSignalMapper [as 别名]
# 或者: from PyQt4.QtCore.QSignalMapper import setMapping [as 别名]
class CollectionAggregator (SatyrObject):
def __init__ (self, parent, collections=None, songs=None, busName=None, busPath=None):
SatyrObject.__init__ (self, parent, busName, busPath)
self.configValues= (
('collsNo', int, 0),
)
self.loadConfig ()
self.signalMapper= QSignalMapper ()
self.collections= []
if songs is None:
self.songs= []
self.count= 0
else:
self.songs= songs
self.count= len (songs)
# if collections is not None we it means the may have changed
if self.collsNo>0 and collections is None:
logger.info ("loading collections from config", self.collsNo)
for index in xrange (self.collsNo):
collection= Collection (self, busName=busName, busPath="/collection_%04d" % index)
self.append (collection)
else:
if collections is not None:
for collection in collections:
self.append (collection)
self.signalMapper.mapped.connect (self.addSongs)
def append (self, collection):
logger.debug ("adding collection", collection)
collection.loadOrScan ()
self.collections.append (collection)
self.collsNo= len (self.collections)
index= len (self.collections)-1
collection.newSongs.connect (self.signalMapper.map)
self.signalMapper.setMapping (collection, index)
collection.scanFinished.connect (self.updateIndexes)
self.updateIndexes ()
def indexToCollection (self, index):
"""Selects the collection that contains the index"""
prevCollection= self.collections[0]
for collection in self.collections[1:]:
# print index, collection.offset
if index < collection.offset:
break
prevCollection= collection
return prevCollection
def indexToCollectionIndex (self, index):
"""Converts a global index to a index in a collection"""
collection= self.indexToCollection (index)
collectionIndex= index-collection.offset
return collection, collectionIndex
def songForIndex (self, index):
if len (self.songs)==0:
# we're not a queue PLM, so we use the collections
collection, collectionIndex= self.indexToCollectionIndex (index)
song= collection.songs[collectionIndex]
else:
song= self.songs[index]
return song
def indexForSong (self, song):
logger.debug ("PLM.indexForSong", song)
index= None
if len (self.songs)>0:
index= self.songs.index (song)
else:
collection= song.coll
collectionIndex= collection.indexForSong (song)
if collectionIndex is not None:
index= collection.offset+collectionIndex
return index
def addSongs (self, collNo):
collection= self.collections[collNo]
# BUG? shouldn't we call updateIndexes?
# HINT: we call it when scanFinished()
self.count+= len (collection.newSongs_)
def updateIndexes (self):
# recalculate the count and the offsets
# only if we don't hols the songs ourselves
if len (self.songs)==0:
# HINT: yes, self.count==offset, but the semantic is different
# otherwise the update of offsets will not be so clear
self.count= 0
offset= 0
#.........这里部分代码省略.........