本文整理汇总了Python中PyQt4.QtGui.QMenu.clear方法的典型用法代码示例。如果您正苦于以下问题:Python QMenu.clear方法的具体用法?Python QMenu.clear怎么用?Python QMenu.clear使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtGui.QMenu
的用法示例。
在下文中一共展示了QMenu.clear方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Main
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
class Main(plugin.Plugin):
" Main Class "
def initialize(self, *args, **kwargs):
" Init Main Class "
super(Main, self).initialize(*args, **kwargs)
if linux_distribution():
self.menu = QMenu('Open with')
self.menu.aboutToShow.connect(self.build_submenu)
self.ex_locator = self.locator.get_service('explorer')
self.ex_locator.add_project_menu(self.menu, lang='all')
def build_submenu(self):
''' build sub menu on the fly based on file path '''
self.menu.clear()
if self.ex_locator.get_current_project_item().isFolder is not True:
filenam = self.ex_locator.get_current_project_item().get_full_path()
entry = xdg_query('default', guess_type(filenam, strict=False)[0])
if entry:
app = entry.replace('.desktop', '')
self.menu.addActions([
QAction(QIcon.fromTheme(app), app, self,
triggered=lambda: Popen([app, filenam])),
QAction(QIcon.fromTheme('folder-open'), 'File Manager',
self, triggered=lambda: Popen(['xdg-open',
path.dirname(filenam)]))])
self.menu.show()
示例2: Main
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
class Main(plugin.Plugin):
" Main Class "
def initialize(self, *args, **kwargs):
" Init Main Class "
super(Main, self).initialize(*args, **kwargs)
self.menu = QMenu('Convert Image')
self.menu.aboutToShow.connect(self.build_submenu)
self.ex_locator = self.locator.get_service('explorer')
self.ex_locator.add_project_menu(self.menu, lang='all')
def build_submenu(self):
''' build sub menu on the fly based on file path '''
self.menu.clear()
if self.ex_locator.get_current_project_item().isFolder is not True:
filenam = self.ex_locator.get_current_project_item().get_full_path()
# pillow.readthedocs.org/en/latest/handbook/image-file-formats.html
exten = ('bmp', 'cur', 'gbr', 'gif', 'ico', 'jfif', 'jpeg', 'pbm',
'pcx', 'pgm', 'png', 'ppm', 'psd', 'tga', 'tiff', 'xbm', 'xpm')
conditional = path.splitext(filenam)[1][1:].strip().lower() in exten
if conditional:
self.menu.addActions([
QAction('{} to WEBP'.format(path.basename(filenam)[:50]),
self, triggered=lambda: self.convert_img('WEBP')),
QAction('{} to JPG'.format(path.basename(filenam)[:50]),
self, triggered=lambda: self.convert_img('JPEG')),
QAction('{} to PNG'.format(path.basename(filenam)[:50]),
self, triggered=lambda: self.convert_img('PNG')), ])
self.menu.show()
def convert_img(self, fmt):
""" convert image to desired format """
filenam = self.ex_locator.get_current_project_item().get_full_path()
im = Image.open(filenam).convert("RGB")
im.save(path.splitext(filenam)[0] + ".{}".format(fmt.lower()), fmt)
示例3: rot13box
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
class rot13box(QWidget):
def __init__(self, parent):
super(rot13box, self).__init__(parent)
self.entry = None
self.but = None
self.buffer = None
self.entry = QLineEdit(self)
self.but = QPushButton("ROT13", self)
if self.buffer is not None:
self.encodeText(self.buffer)
layout = QHBoxLayout(self)
grabButton = QToolButton(parent)
grabButton.setText("Msg ")
# grabButton.setMinimumHeight(self.but.sizeHint().height())
self.msgMenu = QMenu(grabButton)
self.msgMenu.aboutToShow.connect(self.updateMsgMenu)
grabButton.setMenu(self.msgMenu)
grabButton.setPopupMode(QToolButton.InstantPopup)
# grabButton.clicked.connect(self.grabMessage)
layout.addWidget(grabButton)
layout.addWidget(self.entry)
layout.addWidget(self.but)
self.but.clicked.connect(self.enc)
self.setMaximumHeight(self.sizeHint().height())
self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
@loggingSlot()
def updateMsgMenu(self):
self.msgMenu.clear()
messages = get_server().get_messages()
with messages:
for i in xrange(len(messages) - 1, len(messages) - 1 - min(10, len(messages)), -1):
message = messages[i]
self.msgMenu.addAction(message[2], partial(self.encodeText, message[2]))
def grabMessage(self):
self.encodeText(get_server().get_messages().getLatest()[2])
def encodeText(self, text):
if self.entry is not None:
self.entry.setText(text)
self.enc()
else:
self.buffer = text
@loggingSlot()
def enc(self):
rot13 = string.maketrans(
u"ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz",
u"NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm",
)
plain = self.entry.text()
if plain:
self.entry.setText(string.translate(str(plain.toUtf8()), rot13))
示例4: FlowWidget
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
class FlowWidget( QGraphicsView ):
def __init__( self, parent = None ):
QGraphicsView.__init__( self, parent )
self.setAcceptDrops( True )
self.setScene( FlowScene( self ) )
self.setRenderHints( QPainter.Antialiasing | QPainter.SmoothPixmapTransform )
self.setAlignment( Qt.AlignLeft | Qt.AlignTop )
self.autoConnecter = ItemAutoConnecter( self.scene() )
self.setupMenu()
#self.scrollControl = ScrollControl( self )
#self.scrollControl.setScrollingEnabled( False )
def setupMenu( self ):
self.setContextMenuPolicy( Qt.CustomContextMenu )
self.menu = QMenu( self )
self.connect( self, SIGNAL( 'customContextMenuRequested( const QPoint& )' ), self.slotContextMenu )
def slotContextMenu( self, pos ):
self.menu.clear()
item = self.itemAt( pos )
if isinstance( item, FlowSceneGraphEdge ):
self.menu.addAction( item.delete_action )
self.menu.addAction( self.autoConnecter.action() )
self.autoConnecter.updateAction()
self.menu.exec_( self.mapToGlobal( pos ) )
# Zoom by scroll event
# def wheelEvent( self, event ):
# factor = 1.2
# if event.delta() < 0:
# factor = 1.0 / factor
# self.scale( factor, factor )
# #self.updateZoomValue()
# return QGraphicsView.wheelEvent( self, event )
def dragEnterEvent( self, event ):
if isinstance( event.source(), FlowItemTreeWidget ):
event.acceptProposedAction()
def dragMoveEvent( self, event ):
pass
def dropEvent( self, event ):
type_ = event.source().selectedIndexes()[0].data( Qt.UserRole ).toPyObject()
item = type_()
item.setParent( self )
item.setPos( self.mapToScene( event.pos() ) )
self.scene().addItem( item )
示例5: loadSwitcher
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
def loadSwitcher(self):
lmenu = QMenu()
lmenu.clear()
def loadAct(l):
lmenu.addAction(l, lambda: self.langChangeRequest(l))
for x in self.kbList:
loadAct(x)
lmenu.addSeparator()
lmenu.addAction("Configure", lambda: self.nxkbConfig.show())
lmenu.addAction("About", self.showAbout)
lmenu.addAction("Quit", lambda: sys.exit(0))
self.setContextMenu(lmenu)
self.setIcon(QIcon(self.kbMap[self.currentOpt]))
示例6: OneColumnTree
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
class OneColumnTree(QTreeWidget):
def __init__(self, parent):
QTreeWidget.__init__(self, parent)
self.setItemsExpandable(True)
self.setColumnCount(1)
self.connect(self, SIGNAL('itemActivated(QTreeWidgetItem*,int)'),
self.activated)
# Setup context menu
self.menu = QMenu(self)
self.common_actions = self.setup_common_actions()
def activated(self):
raise NotImplementedError
def set_title(self, title):
self.setHeaderLabels([title])
def setup_common_actions(self):
"""Setup context menu common actions"""
collapse_act = create_action(self,
text=self.tr('Collapse all'),
icon=get_icon('collapse.png'),
triggered=self.collapseAll)
expand_act = create_action(self,
text=self.tr('Expand all'),
icon=get_icon('expand.png'),
triggered=self.expandAll)
return [collapse_act, expand_act]
def update_menu(self):
self.menu.clear()
actions = self.specific_actions()
if actions:
actions.append(None)
actions += self.common_actions
add_actions(self.menu, actions)
def specific_actions(self):
# Right here: add other actions if necessary
# (reimplement this method)
return []
def contextMenuEvent(self, event):
"""Override Qt method"""
self.update_menu()
self.menu.popup(event.globalPos())
示例7: Main
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
class Main(plugin.Plugin):
" Main Class "
def initialize(self, *args, **kwargs):
" Init Main Class "
super(Main, self).initialize(*args, **kwargs)
if linux_distribution():
self.menu = QMenu('Open with')
self.menu.aboutToShow.connect(self.build_submenu)
self.ex_locator = self.locator.get_service('explorer')
self.ex_locator.add_project_menu(self.menu, lang='all')
def build_submenu(self):
''' build sub menu on the fly based on file path '''
self.menu.clear()
if self.ex_locator.get_current_project_item().isFolder is not True:
filenam = self.ex_locator.get_current_project_item().get_full_path()
entry = xdg_query('default', guess_type(filenam, strict=False)[0])
if entry:
app = entry.replace('.desktop', '')
actions = [
QAction(QIcon.fromTheme(app), app, self,
triggered=lambda: Popen([app, filenam])),
QAction(QIcon.fromTheme('folder-open'), 'File Manager',
self, triggered=lambda: Popen(['xdg-open', path.dirname(filenam)]))]
#QAction(QIcon.fromTheme('Sublime Text 2'), 'Sublime',
# self, triggered=lambda: Popen(['sublime-text', filenam])),
#QAction(QIcon.fromTheme('Sqliteman'), 'Sqliteman',
# self, triggered=lambda: Popen(['sqliteman', filenam])),
#QAction(QIcon.fromTheme('Google Chrome'), 'Google Chrome',
# self, triggered=lambda: Popen(['google-chrome', filenam]))
for key in usersettings.commands.keys():
action = QAction(QIcon.fromTheme(key), key,
self, triggered=lambda: Popen([usersettings.commands[key], filenam]))
actions.append(action)
self.menu.addActions(actions)
self.menu.show()
示例8: NotificacionActualizacion
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
class NotificacionActualizacion(QSystemTrayIcon):
""" System Tray Icon """
def __init__(self, parent=None):
QSystemTrayIcon.__init__(self, parent)
self.setIcon(QIcon(":image/edis"))
self.menu = QMenu()
self.setContextMenu(self.menu)
exit_action = self.menu.addAction(self.tr("Close"))
self.thread = Thread()
# Conexiones
self.connect(self.thread,
SIGNAL("updateVersion(QString, QString, bool)"),
self._show_tray)
self.connect(exit_action, SIGNAL("triggered()"), self.hide)
self.setToolTip(self.tr("Buscando actualizaciones..."))
self.thread.start()
def _show_tray(self, version, link, found):
""" Muestra el system tray icon """
if found:
self.menu.clear()
self.setToolTip("")
download_action = self.menu.addAction(self.tr("Descargar!"))
exit_action = self.menu.addAction(self.tr("Cerrar notificación"))
self.connect(download_action, SIGNAL("triggered()"),
lambda: webbrowser.open_new(link))
self.connect(exit_action, SIGNAL("triggered()"), self.hide)
self.showMessage(self.tr("Nueva versión disponible!"),
self.tr("Está disponible una nueva versión de"
" Edis\n"
"versión: {0}.").format(version),
QSystemTrayIcon.Information, 10000)
else:
self.hide()
示例9: Main
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
class Main(plugin.Plugin):
" Main Class "
def initialize(self, *args, **kwargs):
" Init Main Class "
super(Main, self).initialize(*args, **kwargs)
self.menu1 = QMenu('Compress')
self.menu1.aboutToShow.connect(self.build_submenu)
self.ex_locator = self.locator.get_service('explorer')
self.ex_locator.add_project_menu(self.menu1, lang='all')
if not version_info[0] < 3:
self.menu2 = QMenu('Extract')
self.menu2.aboutToShow.connect(self.build_submenu)
self.ex_locator.add_project_menu(self.menu2, lang='all')
def build_submenu(self):
''' build sub menu on the fly based on file path '''
self.menu1.clear()
if self.ex_locator.get_current_project_item().isFolder is True:
folder = self.ex_locator.get_current_project_item().get_full_path()
self.menu1.addActions([
QAction('To ZIP', self, triggered=lambda:
make_archive(folder, 'zip', folder)),
QAction('To TAR', self, triggered=lambda:
make_archive(folder, 'tar', folder)),
QAction('To BZ2', self, triggered=lambda:
make_archive(folder, 'bztar', folder))])
self.menu1.show()
elif not version_info[0] < 3:
self.menu2.clear()
filenam = self.ex_locator.get_current_project_item().get_full_path()
exten = ('zip', 'tar', 'bz2', 'bztar', 'gztar')
conditional = path.splitext(filenam)[1][1:].strip().lower() in exten
if conditional:
self.menu2.addAction(QAction('From {}'.format(
path.splitext(filenam)[1].upper()), self, triggered=lambda:
unpack_archive(filenam, path.dirname(filenam))))
self.menu2.show()
示例10: TrayStarter
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
#.........这里部分代码省略.........
"""
Private slot to start the eric4 compare dialog.
"""
self.__startProc("eric4_compare.py", "--config=%s" % Utilities.getConfigDir())
def __startSqlBrowser(self):
"""
Private slot to start the eric4 sql browser dialog.
"""
self.__startProc("eric4_sqlbrowser.py", "--config=%s" % Utilities.getConfigDir())
def __startIconEditor(self):
"""
Private slot to start the eric4 icon editor dialog.
"""
self.__startProc("eric4_iconeditor.py", "--config=%s" % Utilities.getConfigDir())
def __startQRegExp(self):
"""
Private slot to start the eric4 QRegExp editor dialog.
"""
self.__startProc("eric4_qregexp.py", "--config=%s" % Utilities.getConfigDir())
def __startPyRe(self):
"""
Private slot to start the eric4 Python re editor dialog.
"""
self.__startProc("eric4_re.py", "--config=%s" % Utilities.getConfigDir())
def __showRecentProjectsMenu(self):
"""
Private method to set up the recent projects menu.
"""
self.recentProjects.clear()
self.rsettings.sync()
self.__loadRecentProjects()
self.recentProjectsMenu.clear()
idx = 1
for rp in self.recentProjects:
if idx < 10:
formatStr = '&%d. %s'
else:
formatStr = '%d. %s'
act = self.recentProjectsMenu.addAction(\
formatStr % (idx,
Utilities.compactPath(unicode(rp), self.maxMenuFilePathLen)))
act.setData(QVariant(rp))
idx += 1
def __showRecentMultiProjectsMenu(self):
"""
Private method to set up the recent multi projects menu.
"""
self.recentMultiProjects.clear()
self.rsettings.sync()
self.__loadRecentMultiProjects()
self.recentMultiProjectsMenu.clear()
idx = 1
for rmp in self.recentMultiProjects:
if idx < 10:
formatStr = '&%d. %s'
else:
示例11: Tabs
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
class Tabs(BaseTabs):
"""TabWidget with a context-menu"""
def __init__(self, parent, actions=None):
BaseTabs.__init__(self, parent, actions)
tab_bar = TabBar(self, parent)
self.connect(tab_bar, SIGNAL('move_tab(int,int)'), self.move_tab)
self.connect(tab_bar, SIGNAL('move_tab(long,int,int)'),
self.move_tab_from_another_tabwidget)
self.setTabBar(tab_bar)
self.index_history = []
self.connect(self, SIGNAL('currentChanged(int)'),
self.__current_changed)
tabsc = QShortcut(QKeySequence("Ctrl+Tab"), parent, self.tab_navigate)
tabsc.setContext(Qt.WidgetWithChildrenShortcut)
# Browsing tabs button
browse_button = create_toolbutton(self,
icon=get_icon("browse_tab.png"),
tip=translate("Tabs", "Browse tabs"))
self.browse_tabs_menu = QMenu(self)
browse_button.setMenu(self.browse_tabs_menu)
browse_button.setPopupMode(browse_button.InstantPopup)
self.connect(self.browse_tabs_menu, SIGNAL("aboutToShow()"),
self.update_browse_tabs_menu)
self.setCornerWidget(browse_button)
def update_browse_tabs_menu(self):
"""Update browse tabs menu"""
self.browse_tabs_menu.clear()
for index in range(self.count()):
tab_action = create_action(self, self.tabText(index),
icon=self.tabIcon(index),
toggled=lambda state, index=index:
self.setCurrentIndex(index),
tip=self.tabToolTip(index))
tab_action.setChecked(index == self.currentIndex())
self.browse_tabs_menu.addAction(tab_action)
def __current_changed(self, index):
for _i in self.index_history[:]:
if _i > self.count()-1:
self.index_history.pop(self.index_history.index(_i))
while index in self.index_history:
self.index_history.pop(self.index_history.index(index))
self.index_history.append(index)
def tab_navigate(self):
"""Ctrl+Tab"""
if len(self.index_history) > 1:
last = len(self.index_history)-1
index = self.index_history.pop(last)
self.index_history.insert(0, index)
self.setCurrentIndex(self.index_history[last])
elif len(self.index_history) == 0 and self.count():
self.index_history = [self.currentIndex()]
def move_tab(self, index_from, index_to):
"""Move tab inside a tabwidget"""
self.emit(SIGNAL('move_data(int,int)'), index_from, index_to)
tip, text = self.tabToolTip(index_from), self.tabText(index_from)
icon, widget = self.tabIcon(index_from), self.widget(index_from)
current_widget = self.currentWidget()
self.removeTab(index_from)
self.insertTab(index_to, widget, icon, text)
self.setTabToolTip(index_to, tip)
self.setCurrentWidget(current_widget)
self.emit(SIGNAL('move_tab_finished()'))
def move_tab_from_another_tabwidget(self, tabwidget_from,
index_from, index_to):
"""Move tab from a tabwidget to another"""
self.emit(SIGNAL('move_tab(long,long,int,int)'),
tabwidget_from, id(self), index_from, index_to)
示例12: Interface
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
#.........这里部分代码省略.........
#signals to set box values
for index in xrange(api.ARDUINO_DIGITAL_PIN_NB):
box = self.getboxbynum(index)
QObject.disconnect(sim.pins[index], _PINSIGNAL, box.setChecked)
def loadfile(self):
self.settings.beginGroup("Last opened")
filename = unicode(self.settings.value("firmware", ".").toString())
simklass, filename = self._loadfile(filename)
if not simklass:
self.log("Cancel firmware load.")
return
else:
self.setsim(simklass)
self.settings.setValue("firmware", filename)
self.settings.endGroup()
self.addrecent(filename)
self.writerecentlist()
self.settings.sync()
def loadfilefactory(self, filename):
def loadit():
simklass = self._loadfile(filename, dialog=False)[0]
if simklass:
self.setsim(simklass)
self.addrecent(filename)
return loadit
def _updaterecents(self):
self.design.recent.setEnabled(bool(self.recents))
self.recentsmenu.clear()
if not self.recents:
return
for item in self.recents:
self.recentsmenu.addAction(item, self.loadfilefactory(item))
def _readrecent(self):
self.settings.beginGroup("Recent files")
recents = self.settings.value("list", []).toList()
self.settings.endGroup()
return self._recentlist(recents)
def writerecentlist(self):
self.settings.beginGroup("Recent files")
self.settings.setValue("list", self.recents)
self.settings.endGroup()
def addrecent(self, filename):
if filename in self.recents:
self.recents.remove(filename)
self.recents.insert(0, filename)
#limit to size 5
self.recents = self.recents[:5]
self._updaterecents()
def _recentlist(self, origlist, mostrecent=''):
if mostrecent:
yield mostrecent
count = 1
else:
count = 0
for item in origlist:
if isinstance(item, QVariant):
示例13: QDataTableView
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
#.........这里部分代码省略.........
self.addWaveMenu = QMenu("Add Wave", self.horizontalHeaderMenu)
# Add actions to menu
self.horizontalHeaderMenu.addAction(self.addWaveMenu.menuAction())
self.horizontalHeaderMenu.addAction(self.renameWaveAction)
self.horizontalHeaderMenu.addAction(self.removeWaveAction)
def showHorizontalHeaderMenu(self, point):
"""Display the menu that occurs when right clicking on a column header."""
logicalIndex = self.horizontalHeader().logicalIndexAt(point)
visualIndex = self.horizontalHeader().visualIndex(logicalIndex)
self.selectColumn(logicalIndex)
#print "l: " + str(logicalIndex)
#print "v: " + str(visualIndex)
selectedWave = self.model().waves()[logicalIndex]
# Create helper functions, defined for this specific menu location
def renameWaveHelper():
self.renameWave(selectedWave)
def removeWaveHelper():
#self.removeWave(selectedWave)
self.removeWave(visualIndex)
def addWaveHelper(wave):
self.addWave(wave, visualIndex)
def addNewWaveHelper():
wave = Wave(self._app.waves().findGoodWaveName())
self._app.waves().addWave(wave)
self.addWave(wave, visualIndex)
self.addWaveMenu.clear()
# Add "New Wave" entry
newWaveAction = QAction("New Wave", self.addWaveMenu)
self.addWaveMenu.addAction(newWaveAction)
newWaveAction.triggered.connect(addNewWaveHelper)
# Get current list of waves for "add wave to table" menu
#for wave in self._app.waves().waves().values():
for wave in self._app.model('appWaves').waves():
waveAction = AddWaveAction(wave, self.addWaveMenu)
self.addWaveMenu.addAction(waveAction)
waveAction.addWaveClicked.connect(addWaveHelper)
# Connect actions
self.renameWaveAction.triggered.connect(renameWaveHelper)
self.removeWaveAction.triggered.connect(removeWaveHelper)
self.horizontalHeaderMenu.exec_(self.mapToGlobal(point))
# Disconnect actions. We need to do this or else there will be multiple connections
# when we open the menu again, and the old connections will have strange visualIndex values
self.renameWaveAction.triggered.disconnect(renameWaveHelper)
self.removeWaveAction.triggered.disconnect(removeWaveHelper)
for waveAction in self.addWaveMenu.actions():
try:
waveAction.addWaveClicked.disconnect(addWaveHelper)
except:
waveAction.triggered.disconnect(addNewWaveHelper)
def reset(self):
QTableView.reset(self)
self.resizeRowsToContents()
self.resizeColumnsToContents()
def keyPressEvent(self, event):
"""Capture certain types of keypress events and handle them different ways."""
# When data has been edited, move to the next row in the column and continue editing.
currentIndex = self.currentIndex()
#print "row: " + str(currentIndex.row()) + ", col: " + str(currentIndex.column())
if currentIndex.isValid():
if self.state() == QAbstractItemView.EditingState:
if event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
Util.debug(3, "DataTableView.keyPressEvent", "Enter key pressed in table")
newIndex = self.model().createIndex(currentIndex.row() + 1, currentIndex.column())
self.setCurrentIndex(newIndex)
self.edit(newIndex)
self.setCurrentIndex(newIndex)
return
elif event.key() == Qt.Key_Up:
Util.debug(3, "DataTableView.keyPressEvent", "Up key pressed in table")
newIndex = self.model().createIndex(currentIndex.row() - 1, currentIndex.column())
#print "nrow: " + str(newIndex.row()) + ", ncol: " + str(newIndex.column())
#self.setCurrentIndex(newIndex)
self.setState(QAbstractItemView.NoState)
elif event.key() == Qt.Key_Down:
Util.debug(3, "DataTableView.keyPressEvent", "Down key pressed in table")
newIndex = self.model().createIndex(currentIndex.row() + 1, currentIndex.column())
#print "nrow: " + str(newIndex.row()) + ", ncol: " + str(newIndex.column())
#self.setCurrentIndex(newIndex)
self.setState(QAbstractItemView.NoState)
# Nothing found, so resort to default behavior
QTableView.keyPressEvent(self, event)
示例14: Main
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
#.........这里部分代码省略.........
QLabel('<center><small><i>' + ''.join((__doc__, __version__,
__license__, 'by', __author__))), self.button
))
self.scrollable, self.dock = QScrollArea(), QDockWidget()
self.scrollable.setWidgetResizable(True)
self.scrollable.setWidget(tw)
self.dock.setWindowTitle(__doc__)
self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
self.dock.setWidget(self.scrollable)
ExplorerContainer().addTab(self.dock, "Base64")
self.guimode = QComboBox(self.dock)
self.guimode.addItems(['Full Mode', 'Simple Mode'])
self.guimode.currentIndexChanged.connect(self.guimode_change)
def guimode_change(self):
""" Change from Simple Mode to Full Mode by Hide or Show Widgets """
if self.guimode.currentIndex() is 0:
self.chckbx1.show()
self.chckbx2.show()
self.chckbx3.show()
self.chckbx4.show()
else:
self.chckbx1.hide()
self.chckbx2.hide()
self.chckbx3.hide()
self.chckbx4.hide()
self.chckbx1.setChecked(False)
self.chckbx2.setChecked(True)
self.chckbx3.setChecked(False)
self.chckbx4.setChecked(False)
def build_submenu(self):
''' build sub menu on the fly based on file path '''
self.menu.clear()
if self.ex_locator.get_current_project_item().isFolder is not True:
filenam = self.ex_locator.get_current_project_item().get_full_path()
self.menu.addActions([
QAction('Copy {} as Base64'.format(path.basename(filenam)[:50]),
self, triggered=lambda:
QApplication.clipboard().setText(
'"data:{};charset=utf-8;base64,{}"'.format(
guess_type(filenam, strict=False)[0],
b64encode(open(filenam, "rb").read())))),
QAction('Copy {} as Base64 URL-Safe'.format(
path.basename(filenam)[:50]),
self, triggered=lambda:
QApplication.clipboard().setText(
'"data:{};charset=utf-8;base64,{}"'.format(
guess_type(filenam, strict=False)[0],
urlsafe_b64encode(open(filenam, "rb").read()))))])
self.menu.show()
def run(self):
' run the encoding '
mimetype = guess_type(str(self.infile.text()).strip(), strict=False)[0]
_mime = mimetype if mimetype is not None else self.ask_mime()
fle = str(self.infile.text()).strip().replace('file:///', '/')
encoder = urlsafe_b64encode if self.chckbx4.isChecked() else b64encode
if int(path.getsize(fle)) / 1024 / 1024 >= 1:
QMessageBox.information(self.dock, __doc__,
'''<b style="color:red"> WARNING!: File size is > 1 Megabyte!,<br>
this will take some time, depending your CPU Processing power!.''')
output = '"{}{}{}{}"'.format(
'data:' if self.chckbx2.isChecked() is True else '',
_mime if self.chckbx2.isChecked() is True else '',
';charset=utf-8;base64,' if self.chckbx2.isChecked() is True else '',
示例15: ProfileTableViewer
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import clear [as 别名]
#.........这里部分代码省略.........
def __onEsc( self ):
" Triggered when Esc is pressed "
self.escapePressed.emit()
return
def __createContextMenu( self ):
" Creates context menu for the table raws "
self.__contextMenu = QMenu( self )
self.__callersMenu = QMenu( "Callers", self )
self.__outsideCallersMenu = QMenu( "Outside callers", self )
self.__calleesMenu = QMenu( "Callees", self )
self.__outsideCalleesMenu = QMenu( "Outside callees", self )
self.__contextMenu.addMenu( self.__callersMenu )
self.__contextMenu.addMenu( self.__outsideCallersMenu )
self.__contextMenu.addSeparator()
self.__contextMenu.addMenu( self.__calleesMenu )
self.__contextMenu.addMenu( self.__outsideCalleesMenu )
self.__contextMenu.addSeparator()
self.__disasmAct = self.__contextMenu.addAction(
PixmapCache().getIcon( 'disasmmenu.png' ),
"Disassemble", self.__onDisassemble )
self.__callersMenu.triggered.connect( self.__onCallContextMenu )
self.__outsideCallersMenu.triggered.connect( self.__onCallContextMenu )
self.__calleesMenu.triggered.connect( self.__onCallContextMenu )
self.__outsideCalleesMenu.triggered.connect( self.__onCallContextMenu )
self.__table.setContextMenuPolicy( Qt.CustomContextMenu )
self.__table.customContextMenuRequested.connect( self.__showContextMenu )
return
def __showContextMenu( self, point ):
" Context menu "
self.__callersMenu.clear()
self.__outsideCallersMenu.clear()
self.__calleesMenu.clear()
self.__outsideCalleesMenu.clear()
# Detect what the item was clicked
item = self.__table.itemAt( point )
funcName = item.getFunctionName()
self.__disasmAct.setEnabled( item.getFileName() != "" and \
not funcName.startswith( "<" ) )
# Build the context menu
if item.callersCount() == 0:
self.__callersMenu.setEnabled( False )
self.__outsideCallersMenu.setEnabled( False )
else:
callers = self.__stats.stats[ item.getFuncIDs() ][ 4 ]
callersList = callers.keys()
callersList.sort()
for callerFunc in callersList:
menuText = self.__getCallLine( callerFunc, callers[ callerFunc ] )
if self.__isOutsideItem( callerFunc[ 0 ] ):
act = self.__outsideCallersMenu.addAction( menuText )
else:
act = self.__callersMenu.addAction( menuText )
funcFileName, funcLine, funcName = self.__getLocationAndName( callerFunc )
act.setData( QVariant( funcFileName + ":" + \
str( funcLine ) + ":" + \
funcName ) )
self.__callersMenu.setEnabled( not self.__callersMenu.isEmpty() )
self.__outsideCallersMenu.setEnabled( not self.__outsideCallersMenu.isEmpty() )