本文整理汇总了Python中PyQt4.QtGui.QMenu.actions方法的典型用法代码示例。如果您正苦于以下问题:Python QMenu.actions方法的具体用法?Python QMenu.actions怎么用?Python QMenu.actions使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtGui.QMenu
的用法示例。
在下文中一共展示了QMenu.actions方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: menu_button
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
def menu_button(self, main_action_id, ids, widget):
'''
Creates an :obj:`.OWButton` with a popup-menu and adds it to the parent ``widget``.
'''
id, name, attr_name, attr_value, callback, icon_name = self._expand_id(main_action_id)
b = OWButton(parent=widget)
m = QMenu(b)
b.setMenu(m)
b._actions = {}
QObject.connect(m, SIGNAL("triggered(QAction*)"), b, SLOT("setDefaultAction(QAction*)"))
if main_action_id:
main_action = OWAction(self._plot, icon_name, attr_name, attr_value, callback, parent=b)
QObject.connect(m, SIGNAL("triggered(QAction*)"), main_action, SLOT("trigger()"))
for id in ids:
id, name, attr_name, attr_value, callback, icon_name = self._expand_id(id)
a = OWAction(self._plot, icon_name, attr_name, attr_value, callback, parent=m)
m.addAction(a)
b._actions[id] = a
if m.actions():
b.setDefaultAction(m.actions()[0])
elif main_action_id:
b.setDefaultAction(main_action)
b.setPopupMode(QToolButton.MenuButtonPopup)
b.setMinimumSize(40, 30)
return b
示例2: show
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
def show(position, panel, link, cursor):
"""Shows a context menu.
position: The global position to pop up
panel: The music view panel, giving access to mainwindow and view widget
link: a popplerqt4 LinkBrowse instance or None
cursor: a QTextCursor instance or None
"""
m = QMenu(panel)
# selection? -> Copy
if panel.widget().view.surface().hasSelection():
m.addAction(panel.actionCollection.music_copy_image)
if cursor:
a = m.addAction(icons.get("document-edit"), _("Edit in Place"))
@a.triggered.connect
def edit():
from . import editinplace
editinplace.edit(panel.widget(), cursor, position)
elif link:
a = m.addAction(icons.get("window-new"), _("Open Link in &New Window"))
@a.triggered.connect
def open_in_browser():
import helpers
helpers.openUrl(QUrl(link.url()))
a = m.addAction(icons.get("edit-copy"), _("Copy &Link"))
@a.triggered.connect
def copy_link():
QApplication.clipboard().setText(link.url())
# no actions yet? insert Fit Width/Height
if not m.actions():
m.addAction(panel.actionCollection.music_fit_width)
m.addAction(panel.actionCollection.music_fit_height)
m.addAction(panel.actionCollection.music_zoom_original)
m.addSeparator()
m.addAction(panel.actionCollection.music_sync_cursor)
# help
m.addSeparator()
a = m.addAction(icons.get("help-contents"), _("Help"))
@a.triggered.connect
def help():
import userguide
userguide.show("musicview")
# show it!
if m.actions():
m.exec_(position)
m.deleteLater()
示例3: TableView
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
class TableView(QTableView):
def __init__(self, parent):
QTableView.__init__(self, parent)
# Set the title header
self.header_column_count = 0
self.header = HeaderView(Qt.Horizontal, self)
self.header.setClickable(True)
self.connect(self.header, SIGNAL("right_clicked"), self.displayHeadersActionsMenu)
self.setHorizontalHeader(self.header)
self.setMouseTracking(True)
self.header_menu = QMenu(self)
self.setAlternatingRowColors(True)
def updateHeadersActions(self):
# clean the current actions list:
if self.header_column_count == self.header.count():
# column didn't change
return
self.header_column_count = self.header.count()
for action in self.header_menu.actions():
self.removeAction(action)
for col in xrange(self.header.count()):
col_label = self.model().headerData(col, Qt.Horizontal).toString()
action = QAction(col_label, self.header)
action.setCheckable(True)
action.setChecked(not self.header.isSectionHidden(col))
self.connect(action, SIGNAL("triggered()"), self.updateDisplayedColumns)
self.header_menu.addAction(action)
def displayHeadersActionsMenu(self, event):
self.header_menu.exec_(event.globalPos())
def updateDisplayedColumns(self):
for menu_item_no, menu_item in enumerate(self.header_menu.actions()):
if menu_item.isChecked():
self.header.showSection(menu_item_no)
else:
self.header.hideSection(menu_item_no)
print self.sizeHint()
def parentResizeEvent(self, event):
pass
示例4: menu_sessions
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
def menu_sessions(parent):
m = QMenu(parent)
m.setTitle(_('menu title', '&Session'))
m.triggered.connect(slot_session_action)
import sessions
for name in sessions.sessionNames():
a = m.addAction(name.replace('&', '&&'))
a.setObjectName(name)
qutil.addAccelerators(m.actions())
return m
示例5: menu_file_open_recent
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
def menu_file_open_recent(parent):
m = QMenu(parent)
m.setTitle(_("Open &Recent"))
m.triggered.connect(slot_file_open_recent_action)
import recentfiles
for url in recentfiles.urls():
f = url.toLocalFile()
dirname, basename = os.path.split(f)
text = "{0} ({1})".format(basename, util.homify(dirname))
m.addAction(text).url = url
qutil.addAccelerators(m.actions())
return m
示例6: menu_file_new_from_template
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
def menu_file_new_from_template(parent):
m = QMenu(parent)
m.setTitle(_("New from &Template"))
m.triggered.connect(slot_file_new_from_template_action)
from snippet import model, actions, snippets
groups = {}
for name in sorted(model.model().names()):
variables = snippets.get(name).variables
group = variables.get('template')
if group:
action = actions.action(name, m)
if action:
groups.setdefault(group, []).append(action)
for group in sorted(groups):
for action in groups[group]:
m.addAction(action)
m.addSeparator()
qutil.addAccelerators(m.actions())
return m
示例7: slotShowContextMenu
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
def slotShowContextMenu(self, pos):
hit = self.webview.page().currentFrame().hitTestContent(pos)
menu = QMenu()
if hit.linkUrl().isValid():
a = self.webview.pageAction(QWebPage.CopyLinkToClipboard)
a.setIcon(icons.get("edit-copy"))
a.setText(_("Copy &Link"))
menu.addAction(a)
menu.addSeparator()
a = menu.addAction(icons.get("window-new"), _("Open Link in &New Window"))
a.triggered.connect((lambda url: lambda: self.slotNewWindow(url))(hit.linkUrl()))
else:
if hit.isContentSelected():
a = self.webview.pageAction(QWebPage.Copy)
a.setIcon(icons.get("edit-copy"))
a.setText(_("&Copy"))
menu.addAction(a)
menu.addSeparator()
a = menu.addAction(icons.get("window-new"), _("Open Document in &New Window"))
a.triggered.connect((lambda url: lambda: self.slotNewWindow(url))(self.webview.url()))
if menu.actions():
menu.exec_(self.webview.mapToGlobal(pos))
示例8: MSMainWindow
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
#.........这里部分代码省略.........
convert_icon = QIcon(path.normcase("gui/icons/goto.png"))
convert_.setIcon(convert_icon)
self.fileMenu.addAction(convert_)
a = self.fileMenu.addAction(QIcon(path.normcase("gui/icons/process.png")), "&Launch a batch")
a.setEnabled(False)
b = self.fileMenu.addAction(QIcon(path.normcase("gui/icons/process.png")), "&Merge")
b.setToolTip("Merge MRM file")
# b.setEnabled(False)
self.fileMenu.addSeparator()
#
# for i in xrange(self.MAX_RECENT_FILES):
# a = QAction('', self)
# a.setVisible(False)
# self.fileMenu.addAction(a)
#
# for i in xrange(min(self.MAX_RECENT_FILES, len(self.recentFiles))):
# self.fileMenu.actions()[5+i].setVisible(True)
# self.fileMenu.actions()[5+i].setText(self.recentFiles[i].split('/')[-1])
exit_action = QAction("&Exit", self)
exit_action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Q))
exit_action.setIcon(QIcon(QPixmap(path.normcase("gui/icons/exit.png"))))
self.fileMenu.addAction(exit_action)
self.menuBar().addMenu(self.fileMenu)
self.editMenu = QMenu("&Edit")
self.editMenu.setTearOffEnabled(True)
self.editMenu.addAction(QIcon(path.normcase("gui/icons/edit_undo.png")), "&Undo...")
self.editMenu.addAction(QIcon(path.normcase("gui/icons/edit_redo.png")), "&Redo...")
self.editMenu.actions()[0].setEnabled(False)
self.editMenu.actions()[1].setEnabled(False)
self.editMenu.addSeparator()
self.editMenu.addAction(QIcon(path.normcase("gui/icons/run.png")), "&Preferences")
self.exportMenu = QMenu("&Export...")
self.exportMenu.setIcon(QIcon(path.normcase("gui/icons/file_export.png")))
self.exportMenu.addAction("&Peaklist")
self.exportMenu.addAction("&Clusters intensity matrix")
self.editMenu.addMenu(self.exportMenu)
self.menuBar().addMenu(self.editMenu)
# view
self.viewMenu = QMenu("&View")
self.viewMenu.setTearOffEnabled(True)
self.viewMenu.addAction(
QIcon(path.normcase("gui/icons/window_duplicate")),
"&Cascade View",
self.mdiArea.cascadeSubWindows,
QKeySequence(Qt.CTRL + Qt.Key_K),
)
self.viewMenu.addAction(
QIcon(path.normcase("gui/icons/view_icon")),
"&Title View",
self.mdiArea.tileSubWindows,
QKeySequence(Qt.CTRL + Qt.Key_N),
)
self.viewMenu.addAction(
QIcon(path.normcase("gui/icons/stop_process.png")),
"&Close all subWindows",
self.mdiArea.closeAllSubWindows,
QKeySequence(Qt.CTRL + Qt.Key_W),
)
示例9: registerAction
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
def registerAction(self, action, menuName, callback=None):
""" register an action to the manager's main menu """
if not hasattr(self, '_registeredDbActions'):
self._registeredDbActions = {}
if callback is not None:
invoke_callback = lambda x: self.invokeCallback(callback)
if menuName is None or menuName == "":
self.addAction(action)
if menuName not in self._registeredDbActions:
self._registeredDbActions[menuName] = list()
self._registeredDbActions[menuName].append(action)
if callback is not None:
QObject.connect(action, SIGNAL("triggered(bool)"), invoke_callback)
return True
# search for the menu
actionMenu = None
helpMenuAction = None
for a in self.menuBar.actions():
if not a.menu() or a.menu().title() != menuName:
continue
if a.menu() != self.menuHelp:
helpMenuAction = a
actionMenu = a
break
# not found, add a new menu before the help menu
if actionMenu is None:
menu = QMenu(menuName, self)
if helpMenuAction is not None:
actionMenu = self.menuBar.insertMenu(helpMenuAction, menu)
else:
actionMenu = self.menuBar.addMenu(menu)
menu = actionMenu.menu()
menuActions = menu.actions()
# get the placeholder's position to insert before it
pos = 0
for pos in range(len(menuActions)):
if menuActions[pos].isSeparator() and menuActions[pos].objectName().endswith("_placeholder"):
menuActions[pos].setVisible(True)
break
if pos < len(menuActions):
before = menuActions[pos]
menu.insertAction(before, action)
else:
menu.addAction(action)
actionMenu.setVisible(True) # show the menu
if menuName not in self._registeredDbActions:
self._registeredDbActions[menuName] = list()
self._registeredDbActions[menuName].append(action)
if callback is not None:
QObject.connect(action, SIGNAL("triggered(bool)"), invoke_callback)
return True
示例10: QuestionDlg
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
#.........这里部分代码省略.........
screen = QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
self.btn_start.setMyarg('start')
# print(self.btn_start.getMyarg())
self.connect(self.btn_start, SIGNAL("clicked()"), self.startChoice)
# self.connect(self.w1title, SIGNAL("currentIndexChanged(int)"), self.changeTitle)
# self.connect(self.btn_start2, SIGNAL("clicked()"), self.startChoice)
# self.connect(self.w2title, SIGNAL("currentIndexChanged(int)"), self.changeTitle)
self.btngroup.buttonClicked[int].connect(self.btns_click)
# self.connect(self.btn_start, SIGNAL("myslot(PyQt_PyObject)"), self.myslot)
# self.connect(self.btngroup, SIGNAL("buttonClicked(int)"), lambda:self.btns_click())
def myslot(self, text):
# print(text, self.dict_choices)
self.g_curbtn = text
if self.g_curbtn not in self.dict_choices:
self.btnSysMenu.setFocus()
return
# print(self.btngroup.button(int(self.g_curbtn)).parent())
# print(type(self.btngroup.button(int(self.g_curbtn)).parentWidget()))
pos = self.btngroup.button(int(self.g_curbtn)).parent().mapToGlobal(self.btngroup.button(int(self.g_curbtn)).pos())
width = self.btngroup.button(int(self.g_curbtn)).rect().height()
# print("-----", pos, width)
pos.setY(pos.y()+width-5)
indx = 0
for istate in self.dict_choices[self.g_curbtn]:
if istate == '1':
self.popMenu.actions()[indx].setEnabled(True)
elif istate == '0':
self.popMenu.actions()[indx].setEnabled(False)
indx += 1
self.popMenu.exec_(pos)
self.btnSysMenu.setFocus()
# def on_context_menu(self, point):
# print(point)
# self.popMenu.exec_(self.button.mapToGlobal(point))
def btns_click(self, btnid):
# curclassname = self.tabWidget.tabText(0)
query = QSqlQuery(self.db)
# cur = conn.cursor()
today = datetime.date.today()
self.g_curbtn = str(btnid).zfill(2)
if self.g_curbtn not in self.dict_choices:
self.btngroup.button(int(self.g_curbtn)).setStyleSheet(stylesheetstr_new)
query.exec_("select count(*) from tmprecord where stusn='" + str(self.g_curbtn) + "'")
query.next()
if query.value(0) == 0:
query.prepare("insert into tmprecord (classname, stusn, datequestion) values (:classname, :stusn, :datequestion)")
query.bindValue(":classname", self.g_curClassName)
query.bindValue(":stusn", self.g_curbtn)
query.bindValue(":datequestion", today)
query.exec_()
self.dict_choices[self.g_curbtn] = "111"
else:
self.btngroup.button(int(self.g_curbtn)).setStyleSheet(stylesheetstr_old)
self.btngroup.button(int(self.g_curbtn)).setIcon(QIcon())
query.exec_("delete from tmprecord where stusn='"+ str(self.g_curbtn) + "'")
self.dict_choices.pop(self.g_curbtn)
示例11: __init__
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
class CFSceneContextMenuMixin:
" Encapsulates the context menu handling "
def __init__(self):
self.menu = None
self.individualMenus = {}
# Scene menu preparation
self.sceneMenu = QMenu()
self.sceneMenu.addAction(getIcon("filesvg.png"), "Save as SVG...", self.parent().onSaveAsSVG)
self.sceneMenu.addAction(getIcon("filepdf.png"), "Save as PDF...", self.parent().onSaveAsPDF)
self.sceneMenu.addAction(getIcon("filepixmap.png"), "Save as PNG...", self.parent().onSaveAsPNG)
self.sceneMenu.addSeparator()
self.sceneMenu.addAction(getIcon("copymenu.png"), "Copy to clipboard", self.parent().copyToClipboard)
# Common menu for all the individually selected items
self.commonMenu = QMenu()
# self.commonMenu.addAction(
# getIcon( "cutmenu.png" ), "Cut (Ctrl+X)", self.onCut )
# self.commonMenu.addAction(
# getIcon( "copymenu.png" ), "Copy (Ctrl+C)", self.onCopy )
# self.commonMenu.addSeparator()
# self.commonMenu.addAction(
# getIcon( "trash.png" ), "Delete (Del)", self.onDelete )
# Non-comment common menu for the individually selected items
self.nonCommentCommonMenu = QMenu()
# self.nonCommentCommonMenu.addAction(
# getIcon( "customcolors.png" ), "Custom colors...",
# self.onCustomColors )
# self.nonCommentCommonMenu.addAction(
# getIcon( "replacetitle.png" ), "Replace text...",
# self.onReplaceText )
# Individual items specific menu: begin
ifContextMenu = QMenu()
ifContextMenu.addAction(getIcon("switchbranches.png"), "Switch branch layout", self.onSwitchIfBranch)
self.individualMenus[IfCell] = ifContextMenu
# Individual items specific menu: end
# Menu for a group of selected items
self.groupMenu = QMenu()
# self.groupMenu.addAction(
# getIcon( "cfgroup.png" ), "Group...",
# self.onGroup )
# self.groupMenu.addAction(
# getIcon( "customcolors.png" ), "Custom colors...",
# self.onCustomColors )
# self.groupMenu.addSeparator()
# self.groupMenu.addAction(
# getIcon( "trash.png" ), "Delete (Del)", self.onDelete )
return
def onContextMenu(self, event):
" Triggered when a context menu should be shown "
selectedItems = self.selectedItems()
selectionCount = len(selectedItems)
if selectionCount == 0:
self.sceneMenu.popup(event.screenPos())
return
if selectionCount == 1:
self.__buildIndividualMenu(selectedItems[0])
else:
self.__buildGroupMenu(selectedItems)
self.menu.popup(event.screenPos())
return
def __buildIndividualMenu(self, item):
" Builds a context menu for the given item "
self.menu = QMenu()
if type(item) in self.individualMenus:
individualPart = self.individualMenus[type(item)]
self.menu.addActions(individualPart.actions())
self.menu.addSeparator()
if not item.isComment():
self.menu.addActions(self.nonCommentCommonMenu.actions())
self.menu.addSeparator()
self.menu.addActions(self.commonMenu.actions())
# Note: if certain items need to be disabled then it should be done
# here
return
def __buildGroupMenu(self, items):
" Builds a context menu for the group of items "
self.menu = QMenu()
self.menu.addActions(self.groupMenu.actions())
# Note: if certain items need to be disabled then it should be done
# here
return
def onSwitchIfBranch(self):
" If primitive should switch the branches "
selectedItems = self.selectedItems()
#.........这里部分代码省略.........
示例12: QuestionDlg
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
#.........这里部分代码省略.........
screen = QDesktopWidget().screenGeometry()
size = self.geometry()
self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2)
self.btn_start.setMyarg('start')
# print(self.btn_start.getMyarg())
self.connect(self.btn_start, SIGNAL("clicked()"), self.startChoice)
# self.connect(self.w1title, SIGNAL("currentIndexChanged(int)"), self.changeTitle)
self.connect(self.btn_start2, SIGNAL("clicked()"), self.startChoice)
# self.connect(self.w2title, SIGNAL("currentIndexChanged(int)"), self.changeTitle)
self.btngroup.buttonClicked[int].connect(self.btns_click)
# self.connect(self.btn_start, SIGNAL("myslot(PyQt_PyObject)"), self.myslot)
# self.connect(self.btngroup, SIGNAL("buttonClicked(int)"), lambda:self.btns_click())
def myslot(self, text):
# print(text)
self.g_curbtn = text
if self.g_curbtn not in self.dict_choices:
self.btnSysMenu.setFocus()
return
# print(self.btngroup.button(int(self.g_curbtn)).parent())
# print(type(self.btngroup.button(int(self.g_curbtn)).parentWidget()))
pos = self.btngroup.button(int(self.g_curbtn)).parent().mapToGlobal(self.btngroup.button(int(self.g_curbtn)).pos())
width = self.btngroup.button(int(self.g_curbtn)).rect().height()
# print("-----", pos, width)
pos.setY(pos.y()+width-5)
indx = 0
for istate in self.dict_choices[self.g_curbtn]:
if istate == '1':
self.popMenu.actions()[indx].setEnabled(True)
elif istate == '0':
self.popMenu.actions()[indx].setEnabled(False)
indx += 1
self.popMenu.exec_(pos)
self.btnSysMenu.setFocus()
# def on_context_menu(self, point):
# print(point)
# self.popMenu.exec_(self.button.mapToGlobal(point))
def btns_click(self, btnid):
# print(self.btngroup.button(btnid).rect())
# print(self.mapToGlobal(self.btngroup.button(btnid).pos()))
cur = conn.cursor()
today = datetime.date.today()
self.g_curbtn = str(btnid).zfill(4)
if self.g_curbtn not in self.dict_choices:
self.btngroup.button(int(self.g_curbtn)).setStyleSheet(stylesheetstr_new)
cur.execute("select count(*) from tmprecord where studentsn='" + str(self.g_curbtn) + "'")
if cur.fetchall()[0][0] == 0:
strsql = "insert into tmprecord values (?, ?, ?)"
cur.execute(strsql, (None, self.g_curbtn, today))
conn.commit()
self.dict_choices[self.g_curbtn] = "111"
else:
self.btngroup.button(int(self.g_curbtn)).setStyleSheet(stylesheetstr_old)
self.btngroup.button(int(self.g_curbtn)).setIcon(QIcon())
# cur.execute("select count(*) from tmprecord where studentsn='" + str(self.g_curbtn) + "'")
# print(cur.fetchall())
cur.execute("delete from tmprecord where studentsn='"+ str(self.g_curbtn) + "'")
conn.commit()
self.dict_choices.pop(self.g_curbtn)
self.btnSysMenu.setFocus()
示例13: QDataTableView
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [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: MSView
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
class MSView(QSplitter):
modifiedContext = pyqtSignal(object)
def __init__(self, widget, parent=None, **kw):
QSplitter.__init__(self, Qt.Horizontal, parent)
self.setFocusPolicy(Qt.StrongFocus)
self.mainWidget = widget
self.addWidget(self.mainWidget)
self.showHide = None
self.subsidiaryWidget = MSQtCanvas([], "", flags='spectrum')#, subsidiaryWidget=True)
self.subsidiaryWidget.pw.plotItem.toolBar.hide()
self.subsidiaryWidget.setContextMenuPolicy(Qt.CustomContextMenu)
self.connect(self.subsidiaryWidget, SIGNAL("customContextMenuRequested(const QPoint &)"), self.showContextMenu)
self.menu=QMenu(self.subsidiaryWidget)
self.menu.addAction("&Hide...")
self.connect(self.menu.actions()[0], SIGNAL("triggered()"), self.subsidiaryWidget.hide)
self.addWidget(self.subsidiaryWidget)
self.subsidiaryWidget.hide()
self.barplotdrawn = False
self.connect(self.mainWidget, SIGNAL('drawSpectraRequested'), self.drawSpectrum)
self.connect(self.mainWidget, SIGNAL('drawSpectra(PyQt_PyObject, PyQt_PyObject, PyQt_PyObject)'), self.drawSpectra)
self.connect(self.mainWidget, SIGNAL('drawSpectrumByTime'), self.drawSpectrumByTime)
self.connect(self.mainWidget, SIGNAL('hideRequested'), self.subsidiaryWidget.hide)
def showContextMenu(self, pos):
if self.subsidiaryWidget.pw.plotItem.vb.hasMoved:
return self.menu.exec_(QCursor.pos())
@pyqtSlot()
def drawSpectrum(self, p):
if p is None:
return
mergedSpectra=p.merge(p.spectra)
self.subsidiaryWidget.pw.clear()
self.subsidiaryWidget._plotting([mergedSpectra])
self.subsidiaryWidget.pw.setTitle("Merged [email protected]%s-%s"%(str(p.rtmin), str(p.rtmax)))
self.subsidiaryWidget.show()
def drawSpectrumByTime(self, t, sample):
if not sample or not t:
print "unknown error..."
return
spectra = sample.spectraInRTRange(t.x(), t.x()-2., t.x()+2.)
if not spectra:
print "No spectrum found at this retention time"
return
closest = sorted(spectra, key=lambda x: abs(t.x()-x.rtmin))[0]
self.subsidiaryWidget.pw.clear()
self.subsidiaryWidget._plotting([closest])
self.subsidiaryWidget.pw.setTitle("[email protected]%s"%(str(closest.rtmin)))
self.subsidiaryWidget.show()
def drawSpectra(self, inf, sup, sample):
if not sample:
return
spectra = sample.spectraInRTRange((inf+sup)/2., inf, sup)
print [s.rtmin for s in spectra]
示例15: MSQtCanvas
# 需要导入模块: from PyQt4.QtGui import QMenu [as 别名]
# 或者: from PyQt4.QtGui.QMenu import actions [as 别名]
#.........这里部分代码省略.........
self.smoothButton=QToolButton()
#self.smoothButton.setToolButtonStyle(2)
self.smoothButton.setPopupMode(2)
self.smoothButton.setToolTip("Smooth the visualized data")
#self.smoothButton.setText("Smooth...")
self.smoothButton.setIcon(QIcon(os.path.normcase('gui/icons/smooth.png')))
self.smoothMenu = QMenu()
self.connect(self.smoothMenu, SIGNAL('triggered(QAction*)'), self.smooth)
self.smoothButton.setMenu(self.smoothMenu)
self.pw.plotItem.toolBar.addWidget(self.smoothButton)
self.flipButton=QToolButton()
#self.flipButton.setToolButtonStyle(2)
self.flipButton.setIcon(QIcon(os.path.normcase('gui/icons/flip.png')))
self.flipButton.setToolTip("Flip the visualized data")
#self.flipButton.setText("Flip...")
self.flipButton.setPopupMode(2)
self.flipMenu = QMenu()
self.connect(self.flipMenu, SIGNAL('triggered(QAction*)'), self.flip)
self.flipButton.setMenu(self.flipMenu)
self.pw.plotItem.toolBar.addWidget(self.flipButton)
self.annotButton=QToolButton()
#self.annotButton.setToolButtonStyle(2)
self.annotButton.setPopupMode(2)
#self.annotButton.setText("&Annotate...")
self.annotButton.setIcon(QIcon(os.path.normcase('gui/icons/attach.png')))
self.annotMenu = QMenu()
self.annotMenu.addAction("&Add Annotation")
self.annotMenu.addAction("&Remove last Annotation")
self.annotMenu.addAction("&Remove All Annotation")
self.annotButton.setMenu(self.annotMenu)
self.connect(self.annotMenu.actions()[0], SIGNAL("triggered()"), self.annotate)
self.connect(self.annotMenu.actions()[1], SIGNAL("triggered()"), self.removeLastAnnot)
self.connect(self.annotMenu.actions()[2], SIGNAL("triggered()"), self.removeAllAnnot)
self.pw.plotItem.toolBar.addWidget(self.annotButton)
self.addPlotButton=QToolButton()
#self.addPlotButton.setToolButtonStyle(2)
self.addPlotButton.setText("Add...")
self.addPlotButton.setIcon(QIcon(os.path.normcase('gui/icons/list_add.png')))
self.addPlotButton.setToolTip("Add a new plot to the current figure")
#self.addPlotButton.setText('&Add Plot')
self.pw.plotItem.toolBar.addWidget(self.addPlotButton)
self.showSpectra=QToolButton()
self.showSpectra.setPopupMode(2) #instant popup
#self.showSpectra.setToolButtonStyle(2)
self.showSpectra.setIcon(QIcon(os.path.normcase('gui/icons/file_export.png')))
#self.showSpectra.setText('&Show /hide...')
self.showSpectra.setToolTip('Show/hide ...')
self.showMenu=QMenu()
self.showTextLabels=QAction("&Show Labels", self.showMenu)
self.showTextLabels.setCheckable(True)
self.showTextLabels.setChecked(True)
self.showMenu.addAction(self.showTextLabels)
self.connect(self.showMenu.actions()[0], SIGNAL('toggled(bool)'), self.setTextLabelsVisibility)
showSpectrum=QAction("&Merged Spectrum", self.showMenu)
showSpectrum.setCheckable(True)
if self.flags == 'chroma' or self.flags == 'spectra':
showSpectrum.setEnabled(False)
self.showMenu.addAction(showSpectrum)
self.connect(self.showMenu.actions()[1], SIGNAL('toggled(bool)'), self.drawSpectraRequested)
showNonXCMSPeak=QAction("&Show Non XCMS Peak", self.showMenu)