本文整理汇总了Python中PyQt4.QtGui.QListView.setModel方法的典型用法代码示例。如果您正苦于以下问题:Python QListView.setModel方法的具体用法?Python QListView.setModel怎么用?Python QListView.setModel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtGui.QListView
的用法示例。
在下文中一共展示了QListView.setModel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
def __init__(self, model, enlargeFunction, parent):
QWidget.__init__(self, parent)
def enlarge(index):
enlargeFunction(model.list[index.row()])
windowSize = self.window().frameSize()
self.resize(QSize(windowSize.width()-(25+utilities.bigCardSize[0]),275))
lvViewer = QListView(self)
lvViewer.setModel(model)
lvViewer.setDragEnabled(True)
lvViewer.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
lvViewer.setFlow(QListView.LeftToRight)
lvViewer.setFocus()
self.connect(lvViewer, SIGNAL('clicked(QModelIndex)'), enlarge)
button = QPushButton("Close", self)
self.connect(button,SIGNAL('clicked()'),self.hide)
layout = QVBoxLayout(self)
layout.addWidget(QLabel("I'm sorry this is so ugly.",self))
layout.addWidget(lvViewer)
layout.addWidget(button)
self.setLayout(layout)
self.show()
示例2: displayExile
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
def displayExile(self):
from PyQt4.QtGui import QListView, QAbstractItemView, QPushButton, QVBoxLayout, QLabel
from PyQt4.QtCore import QSize
from util import utilities
windowSize = self.window().frameSize()
self.viewer = QWidget(self.window())
self.viewer.move(10,10)
self.viewer.resize(QSize(windowSize.width()-(25+utilities.bigCardSize[0]),275))
lvViewer = QListView(self.viewer)
lvViewer.setModel(self.model)
lvViewer.setDragEnabled(True)
lvViewer.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
lvViewer.setFlow(QListView.LeftToRight)
lvViewer.setFocus()
self.connect(lvViewer, SIGNAL('clicked(QModelIndex)'), self.enlarge)
button = QPushButton("Close", self.viewer)
self.connect(button,SIGNAL('clicked()'),self.hideViewer)
layout = QVBoxLayout(self)
layout.addWidget(QLabel("I'm sorry this is so ugly.",self.viewer))
layout.addWidget(lvViewer)
layout.addWidget(button)
self.viewer.setLayout(layout)
self.viewer.show()
示例3: ResultWin
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
class ResultWin(QMainWindow):
""" Window use to display pylint results """
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.parent = parent
try:
self.setAttribute(Qt.WA_Maemo5AutoOrientation, True)
except AttributeError:
pass
self.list_view = QListView()
self.list_model = ResultModel()
self.list_view.setViewMode(QListView.ListMode)
self.list_view.setWordWrap(True)
self.list_view.setResizeMode(QListView.Adjust)
self.list_view.setModel(self.list_model)
self.setCentralWidget(self.list_view)
def set_results(self, results):
""" Set the tuple in the model """
self.list_model.set_data(results)
def append_results(self, results):
""" Append the tuple in the model """
self.list_model.append_data(results)
示例4: test_dock_standalone
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
def test_dock_standalone(self):
widget = QWidget()
layout = QHBoxLayout()
widget.setLayout(layout)
layout.addStretch(1)
widget.show()
dock = CollapsibleDockWidget()
layout.addWidget(dock)
list_view = QListView()
list_view.setModel(QStringListModel(["a", "b"], list_view))
label = QLabel("A label. ")
label.setWordWrap(True)
dock.setExpandedWidget(label)
dock.setCollapsedWidget(list_view)
dock.setExpanded(True)
self.app.processEvents()
def toogle():
dock.setExpanded(not dock.expanded())
self.singleShot(2000, toogle)
toogle()
self.app.exec_()
示例5: AppletNoticeWindow
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
class AppletNoticeWindow(QWidget):
def __init__(self, controller):
QWidget.__init__(self)
self.__controller = controller
self.__pkglist = []
# setup widgets
self.__vbox_up = QVBoxLayout()
self.__critical_label = QLabel()
self.__critical_label.setWordWrap(True)
self.__list_model = QStringListModel()
self.__list_view = QListView()
self.__list_view.setModel(self.__list_model)
self.__vbox_up.addWidget(self.__critical_label)
self.__vbox_up.addWidget(self.__list_view)
# bottom buttons
self.__vbox = QVBoxLayout()
self.__vbox.addLayout(self.__vbox_up)
self.__button_hbox = QHBoxLayout()
self.__close_button = QPushButton(_("Close"))
self.__launch_pm_button = QPushButton(_("Launch Application Browser"))
self.__button_hbox.addWidget(self.__launch_pm_button)
self.__button_hbox.addWidget(self.__close_button)
self.__vbox.addLayout(self.__button_hbox)
self.setLayout(self.__vbox)
# set window settings
self.resize(400, 200)
self.setWindowTitle(_("Application updates"))
self.connect(self.__close_button, SIGNAL("clicked()"), self.on_close)
self.connect(self.__launch_pm_button, SIGNAL("clicked()"), self.on_pm)
def closeEvent(self, event):
"""
We don't want to kill the window, since the whole app will close
otherwise.
"""
event.ignore()
self.on_close()
def on_pm(self):
self.__controller.launch_package_manager()
def on_close(self):
self.__controller.trigger_notice_window()
def populate(self, pkg_data, critical_txt):
self.__list_model.setStringList(pkg_data)
self.__critical_label.setText(critical_txt)
self.__list_view.update()
示例6: __init__
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
view = QListView()
view.setDragEnabled(True)
view.setAcceptDrops(True)
view.setDropIndicatorShown(True)
view.setSelectionMode(view.ExtendedSelection)
self.model = ListModel(view)
view.setModel(self.model)
self.setCentralWidget(view)
示例7: VariableComboBox
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
class VariableComboBox(QWidget):
def __init__(self, id, text="Input data", default=[], model=None):
QWidget.__init__(self)
self.setToolTip("<p>Select input dataset</p>")
self.id = id
if model is None:
self.model = TreeModel()
else:
self.model = model
self.comboBox = QComboBox()
self.treeView = QListView(self.comboBox)
self.connect(self.comboBox, SIGNAL("currentIndexChanged(int)"),
self.changeSelectedText)
self.proxyModel = SortFilterProxyModel()
self.proxyModel.setDynamicSortFilter(True)
self.proxyModel.setFilterKeyColumn(1)
self.proxyModel.setSourceModel(self.model)
regexp = QRegExp("|".join([r"%s" % i for i in default]))
self.proxyModel.setFilterRegExp(regexp)
# self.treeView.header().hide()
self.currentText = QString()
self.treeView.setModel(self.proxyModel)
self.comboBox.setModel(self.proxyModel)
self.comboBox.setView(self.treeView)
# self.treeView.hideColumn(1)
# self.treeView.hideColumn(2)
# self.treeView.hideColumn(3)
self.treeView.viewport().installEventFilter(self.comboBox)
label = QLabel(text)
hbox = HBoxLayout()
hbox.addWidget(label)
hbox.addWidget(self.comboBox)
self.setLayout(hbox)
self.changeSelectedText(None)
def changeSelectedText(self, index):
item = self.treeView.currentIndex()
if not item.isValid():
item = self.proxyModel.index(0,0, QModelIndex())
tree = self.treeView.model().parentTree(item)
self.currentText = tree
def parameterValues(self):
return {self.id:self.currentText}
示例8: QuickAccessWidget
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
class QuickAccessWidget(QFrame):
def __init__(self, parent):
QFrame.__init__(self, parent)
self.setFrameStyle(QFrame.Box | QFrame.Sunken)
self.setStyleSheet("QListView {background: transparent; }")
self.setLayout(QHBoxLayout())
self.layout().setContentsMargins(0, 0, 0, 0)
self.listView = QListView(self)
self.layout().addWidget(self.listView)
self.listView.setModel(self.window().quickAccessModel)
self.listView.setMovement(QListView.Snap)
self.listView.setFlow(QListView.LeftToRight)
self.listView.setResizeMode(QListView.Adjust)
gridSize = self.logicalDpiX() / 96 * 60
self.listView.setGridSize(QSize(gridSize, gridSize))
self.listView.setViewMode(QListView.IconMode)
self.listView.activated.connect(self.listView.model().runShortcut)
示例9: widget
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
def widget(self,parent):
td = ListPickerDialog(self, parent)
td.setWindowTitle("Select Server")
td.setAttribute(Qt.WA_DeleteOnClose)
layout = QHBoxLayout();
layout.setContentsMargins(16, 0, 16, 8)
view = self.view()
if not view:
listView = QListView()
listView.setEditTriggers( QAbstractItemView.NoEditTriggers)
listView.setModel(self.model())
listView.setModelColumn(self.modelColumn())
if listView.sizeHintForRow(0)>0:
listView.setMinimumHeight(listView.sizeHintForRow(0) * 5)
view = listView
else:
view.setModel(self.model())
layout.addWidget(view)
self.setView(view)
if self.model():
index = self.model().index(self.currentIndex(), self.modelColumn())
self.selectModelIndex(index)
btnbox = QDialogButtonBox(Qt.Vertical)
btnbox.addButton("Select", QDialogButtonBox.AcceptRole)
addBtn = btnbox.addButton("Add", QDialogButtonBox.ActionRole)
addBtn.clicked.connect(self.addServer)
editBtn = btnbox.addButton("Edit", QDialogButtonBox.ActionRole)
editBtn.clicked.connect(self.editServer)
remBtn = btnbox.addButton("Remove", QDialogButtonBox.ActionRole)
remBtn.clicked.connect(self.remServer)
btnbox.accepted.connect( td.accept)
btnbox.rejected.connect( td.reject)
layout.addWidget(btnbox)
td.setLayout(layout)
return td
示例10: OWPySparkScript
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
class OWPySparkScript(SharedSparkContext, widget.OWWidget):
priority = 3
name = "PySpark Script"
description = "Write a PySpark script and run it on input"
icon = "../icons/PythonScript.svg"
inputs = [("in_object", object, "setObject")]
outputs = [("out_object", object, widget.Dynamic)]
libraryListSource = \
Setting([Script("Hello world", "print('Hello world')\n")])
currentScriptIndex = Setting(0)
splitterState = Setting(None)
auto_execute = Setting(False)
def __init__(self):
super().__init__()
self.in_data = None
self.in_distance = None
self.in_learner = None
self.in_classifier = None
self.in_object = None
self.auto_execute = False
for s in self.libraryListSource:
s.flags = 0
self._cachedDocuments = { }
self.infoBox = gui.widgetBox(self.controlArea, 'Info')
gui.label(
self.infoBox, self,
"<p>Execute python script.</p><p>Input variables:<ul><li> " + \
"<li>".join(t.name for t in self.inputs) + \
"</ul></p><p>Output variables:<ul><li>" + \
"<li>".join(t.name for t in self.outputs) + \
"</ul></p>"
)
self.libraryList = itemmodels.PyListModel(
[], self,
flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable)
self.libraryList.wrap(self.libraryListSource)
self.controlBox = gui.widgetBox(self.controlArea, 'Library')
self.controlBox.layout().setSpacing(1)
self.libraryView = QListView(
editTriggers = QListView.DoubleClicked |
QListView.EditKeyPressed,
sizePolicy = QSizePolicy(QSizePolicy.Ignored,
QSizePolicy.Preferred)
)
self.libraryView.setItemDelegate(ScriptItemDelegate(self))
self.libraryView.setModel(self.libraryList)
self.libraryView.selectionModel().selectionChanged.connect(
self.onSelectedScriptChanged
)
self.controlBox.layout().addWidget(self.libraryView)
w = itemmodels.ModelActionsWidget()
self.addNewScriptAction = action = QAction("+", self)
action.setToolTip("Add a new script to the library")
action.triggered.connect(self.onAddScript)
w.addAction(action)
action = QAction(unicodedata.lookup("MINUS SIGN"), self)
action.setToolTip("Remove script from library")
action.triggered.connect(self.onRemoveScript)
w.addAction(action)
action = QAction("Update", self)
action.setToolTip("Save changes in the editor to library")
action.setShortcut(QKeySequence(QKeySequence.Save))
action.triggered.connect(self.commitChangesToLibrary)
w.addAction(action)
action = QAction("More", self, toolTip = "More actions")
new_from_file = QAction("Import a script from a file", self)
save_to_file = QAction("Save selected script to a file", self)
save_to_file.setShortcut(QKeySequence(QKeySequence.SaveAs))
new_from_file.triggered.connect(self.onAddScriptFromFile)
save_to_file.triggered.connect(self.saveScript)
menu = QMenu(w)
menu.addAction(new_from_file)
menu.addAction(save_to_file)
action.setMenu(menu)
button = w.addAction(action)
button.setPopupMode(QToolButton.InstantPopup)
w.layout().setSpacing(1)
#.........这里部分代码省略.........
示例11: EkdSaveDialog
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
class EkdSaveDialog(QDialog):
'''
EkdSaveDialog : Classe représentant la boite de dialogue utiliser lors de
l'enregistrement des modification sur un fichier donné
attributs : suffix - Suffix utilisé en filtre
filter - Filtre (déduit à partir du suffix)
chemin - Chemin du dernier fichier enregistré
multiple - va-t-on enregistrer plus d'un fichier ?
(ex: extraction d'image d'une vidéo)
méthodes : getFile - Invoque la boite de dialogue et retourne
le fichier saisi
'''
### Pourquoi avoir réimplémenté cette classe au lieu de passer par
### QFileDialog ?
## Correction du bug de consommation mémoire
##
## Explication du problème :
## Par défaut un QFileDialog utilise un QFileSystemModel qui lui
## crée un QWatchFileSystem
## Hors QWatchFileSystem scan régulièrement les changement
## dans le répertoire courant
## Ce phénomène provoque une réaction en chaine :
## 1 - je choisi mon répertoire de destination d'enregistrement
## de mes images
## 2 - ffmpeg se lance
## 3 - ffmpeg crée un fichier dans l'arborescence
## 4 - QWatchFileSystem (est toujours dans le répertoire courant)
## détecte un changement
## et recharge l'ensemble du contenue du répertoire
## 5 - goto 3 jusqu'à plus de mémoire ou fin du process ffmpeg
##
##
def __init__(self, parent, path = None, suffix = '', title = u"Sauver",
multiple = False, mode = None):
if type(suffix) == tuple or type(suffix) == list :
sfilter=""
for s in suffix :
sfilter += "*"+s+" "
self.filter=sfilter[:-1]
# Si on a plusieur suffix, on prend le premier par défaut pour
# la sauvegarde
self.suffix = suffix[0]
else :
self.suffix = suffix
self.filter = "*" + self.suffix
QDialog.__init__(self, parent)
self.setWindowTitle(title)
self.multiple = multiple
self.mode = mode
if not path:
if self.mode == "image" :
path = EkdConfig.get("general", "image_output_path")
elif self.mode == "video" :
path = EkdConfig.get("general", "video_output_path")
elif self.mode == "audio" :
path = EkdConfig.get("general", "sound_output_path")
else :
path = unicode(QDir.homePath())
# Nom du répertoire courant
self.location = QLabel("<b>%s</b>" % path)
# Variable permettant de savoir à tout moment le répertoire courant.
self.currentDir = path
self.mkdirButton = QPushButton(u" Créer un répertoire")
self.mkdirButton.setIcon(QIcon("Icones" + os.sep + "add_sub_task.png"))
if int(EkdConfig.get("general", "show_hidden_files")) :
#print "hidden shown"
EkdPrint(u"hidden shown")
shf = QDir.Hidden
else : shf = QDir.Readable
# Liste des fichiers
self.dirList = QListView()
sorting = QDir.DirsFirst
if int(EkdConfig.get("general", "ignore_case")):
sorting |= QDir.IgnoreCase
self.sorting = sorting
self.flags = QDir.Files | QDir.Readable | shf
self.dirModel = QStandardItemModel()
self.dirList.setModel(self.dirModel)
self.updateDir(path)
self.dirList.setWrapping(True)
#panneau latéral
self.dirTree = QTreeView()
self.dirModelLight = QDirModel(QStringList(""), QDir.AllDirs |
QDir.NoDotAndDotDot | shf, QDir.DirsFirst |
QDir.Name | QDir.IgnoreCase)
self.dirTree.setModel(self.dirModelLight)
self.dirTree.setColumnHidden(1,True)
self.dirTree.setColumnHidden(2,True)
self.dirTree.setColumnHidden(3,True)
self.dirTree.setMaximumWidth(200)
self.dirTree.setMinimumWidth(150)
self.dirTree.setCurrentIndex(self.dirModelLight.index(path))
self.dirTree.resizeColumnToContents(0)
#.........这里部分代码省略.........
示例12: DataTypeKeysWidget
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
class DataTypeKeysWidget(QWidget):
dataTypeKeySelected = pyqtSignal(str)
def __init__(self):
QWidget.__init__(self)
self.__filter_popup = FilterPopup(self)
self.__filter_popup.filterSettingsChanged.connect(self.onItemChanged)
layout = QVBoxLayout()
self.model = DataTypeKeysListModel()
self.filter_model = DataTypeProxyModel(self.model)
filter_layout = QHBoxLayout()
self.search_box = SearchBox()
self.search_box.filterChanged.connect(self.setSearchString)
filter_layout.addWidget(self.search_box)
filter_popup_button = QToolButton()
filter_popup_button.setIcon(util.resourceIcon("ide/cog_edit.png"))
filter_popup_button.clicked.connect(self.showFilterPopup)
filter_layout.addWidget(filter_popup_button)
layout.addLayout(filter_layout)
self.data_type_keys_widget = QListView()
self.data_type_keys_widget.setModel(self.filter_model)
self.data_type_keys_widget.selectionModel().selectionChanged.connect(self.itemSelected)
layout.addSpacing(15)
layout.addWidget(self.data_type_keys_widget, 2)
layout.addStretch()
# layout.addWidget(Legend("Default types", DataTypeKeysListModel.DEFAULT_DATA_TYPE))
layout.addWidget(Legend("Observations available", DataTypeKeysListModel.HAS_OBSERVATIONS))
self.setLayout(layout)
def onItemChanged(self, item):
self.filter_model.setShowBlockKeys(item["block"])
self.filter_model.setShowSummaryKeys(item["summary"])
self.filter_model.setShowGenKWKeys(item["gen_kw"])
self.filter_model.setShowGenDataKeys(item["gen_data"])
self.filter_model.setShowCustomPcaKeys(item["custom_pca"])
def itemSelected(self):
selected_item = self.getSelectedItem()
if selected_item is not None:
self.dataTypeKeySelected.emit(selected_item)
def getSelectedItem(self):
""" @rtype: str """
index = self.data_type_keys_widget.currentIndex()
source_index = self.filter_model.mapToSource(index)
item = self.model.itemAt(source_index)
return item
def selectDefault(self):
self.data_type_keys_widget.setCurrentIndex(self.filter_model.index(0, 0))
def setSearchString(self, filter):
self.filter_model.setFilterFixedString(filter)
def showFilterPopup(self):
self.__filter_popup.show()
示例13: __setupUi
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
#.........这里部分代码省略.........
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
combo = QComboBox()
combo.addItems([self.tr("Critical"),
self.tr("Error"),
self.tr("Warn"),
self.tr("Info"),
self.tr("Debug")])
cb = QCheckBox(self.tr("Show output on 'Error'"),
objectName="focus-on-error")
self.bind(combo, "currentIndex", "logging/level")
self.bind(cb, "checked", "output/show-on-error")
layout.addWidget(combo)
layout.addWidget(cb)
box.setLayout(layout)
form.addRow(self.tr("Logging"), box)
box = QWidget()
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
cb1 = QCheckBox(self.tr("Stay on top"),
objectName="stay-on-top")
cb2 = QCheckBox(self.tr("Dockable"),
objectName="output-dockable")
self.bind(cb1, "checked", "output/stay-on-top")
self.bind(cb2, "checked", "output/dockable")
layout.addWidget(cb1)
layout.addWidget(cb2)
box.setLayout(layout)
form.addRow(self.tr("Output window"), box)
box = QWidget()
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
cb1 = QCheckBox(self.tr("Open in external browser"),
objectName="open-in-external-browser")
cb2 = QCheckBox(self.tr("Stay on top"),
objectName="help-stay-on-top")
cb3 = QCheckBox(self.tr("Dockable"),
objectName="help-dockable")
self.bind(cb1, "checked", "help/open-in-external-browser")
self.bind(cb2, "checked", "help/stay-on-top")
self.bind(cb3, "checked", "help/dockable")
layout.addWidget(cb1)
layout.addWidget(cb2)
layout.addWidget(cb3)
box.setLayout(layout)
form.addRow(self.tr("Help window"), box)
tab.setLayout(form)
# Categories Tab
tab = QWidget()
layout = QVBoxLayout()
view = QListView()
from .. import registry
reg = registry.global_registry()
model = QStandardItemModel()
settings = QSettings()
for cat in reg.categories():
item = QStandardItem()
item.setText(cat.name)
item.setCheckable(True)
visible, _ = category_state(cat, settings)
item.setCheckState(Qt.Checked if visible else Qt.Unchecked)
model.appendRow([item])
view.setModel(model)
layout.addWidget(view)
tab.setLayout(layout)
model.itemChanged.connect(
lambda item:
save_category_state(
reg.category(str(item.text())),
_State(item.checkState() == Qt.Checked, -1),
settings
)
)
self.addTab(tab, "Categories")
if self.__macUnified:
# Need some sensible size otherwise mac unified toolbar 'takes'
# the space that should be used for layout of the contents
self.adjustSize()
示例14: SortedListWidget
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
class SortedListWidget(QWidget):
sortingOrderChanged = Signal()
class _MyItemDelegate(QStyledItemDelegate):
def __init__(self, sortingModel, parent):
QStyledItemDelegate.__init__(self, parent)
self.sortingModel = sortingModel
def sizeHint(self, option, index):
size = QStyledItemDelegate.sizeHint(self, option, index)
return QSize(size.width(), size.height() + 4)
def createEditor(self, parent, option, index):
cb = QComboBox(parent)
cb.setModel(self.sortingModel)
cb.showPopup()
return cb
def setEditorData(self, editor, index):
pass # TODO: sensible default
def setModelData(self, editor, model, index):
text = editor.currentText()
model.setData(index, text)
def __init__(self, *args):
QWidget.__init__(self, *args)
self.setContentsMargins(0, 0, 0, 0)
gridLayout = QGridLayout()
gridLayout.setContentsMargins(0, 0, 0, 0)
gridLayout.setSpacing(1)
model = QStandardItemModel(self)
model.rowsInserted.connect(self.__changed)
model.rowsRemoved.connect(self.__changed)
model.dataChanged.connect(self.__changed)
self._listView = QListView(self)
self._listView.setModel(model)
# self._listView.setDragEnabled(True)
self._listView.setDropIndicatorShown(True)
self._listView.setDragDropMode(QListView.InternalMove)
self._listView.viewport().setAcceptDrops(True)
self._listView.setMinimumHeight(100)
gridLayout.addWidget(self._listView, 0, 0, 2, 2)
vButtonLayout = QVBoxLayout()
self._upAction = QAction(
"\u2191", self, toolTip="Move up")
self._upButton = QToolButton(self)
self._upButton.setDefaultAction(self._upAction)
self._upButton.setSizePolicy(
QSizePolicy.Fixed, QSizePolicy.MinimumExpanding)
self._downAction = QAction(
"\u2193", self, toolTip="Move down")
self._downButton = QToolButton(self)
self._downButton.setDefaultAction(self._downAction)
self._downButton.setSizePolicy(
QSizePolicy.Fixed, QSizePolicy.MinimumExpanding)
vButtonLayout.addWidget(self._upButton)
vButtonLayout.addWidget(self._downButton)
gridLayout.addLayout(vButtonLayout, 0, 2, 2, 1)
hButtonLayout = QHBoxLayout()
self._addAction = QAction("+", self)
self._addButton = QToolButton(self)
self._addButton.setDefaultAction(self._addAction)
self._removeAction = QAction("-", self)
self._removeButton = QToolButton(self)
self._removeButton.setDefaultAction(self._removeAction)
hButtonLayout.addWidget(self._addButton)
hButtonLayout.addWidget(self._removeButton)
hButtonLayout.addStretch(10)
gridLayout.addLayout(hButtonLayout, 2, 0, 1, 2)
self.setLayout(gridLayout)
self._addAction.triggered.connect(self._onAddAction)
self._removeAction.triggered.connect(self._onRemoveAction)
self._upAction.triggered.connect(self._onUpAction)
self._downAction.triggered.connect(self._onDownAction)
def sizeHint(self):
size = QWidget.sizeHint(self)
return QSize(size.width(), 100)
def _onAddAction(self):
item = QStandardItem("")
item.setFlags(item.flags() ^ Qt.ItemIsDropEnabled)
self._listView.model().appendRow(item)
self._listView.setCurrentIndex(item.index())
#.........这里部分代码省略.........
示例15: DesktopIconWidget
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import setModel [as 别名]
class DesktopIconWidget(QFrame):
def __init__(self, parent):
QFrame.__init__(self, parent)
self.setFrameStyle(QFrame.Box | QFrame.Sunken)
self.setStyleSheet("QListView{background:transparent;}")
self.listView = QListView(self)
self.setLayout(QHBoxLayout())
self.layout().setContentsMargins(0, 0, 0, 0)
self.layout().addWidget(self.listView)
self.listView.setContextMenuPolicy(Qt.CustomContextMenu)
self.listView.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.listView.setMovement(QListView.Snap)
self.listView.setFlow(QListView.LeftToRight)
self.listView.setResizeMode(QListView.Adjust)
self.listView.setGridSize(QSize(self.logicalDpiX() / 96 * 70,
self.logicalDpiY() / 96 * 70))
self.listView.setViewMode(QListView.IconMode)
self.quickDesktopModel = QuickDesktopModel(self.window().platform.databaseFile)
self.listView.setModel(self.quickDesktopModel)
self.createActions()
self.makeConnections()
def createActions(self):
self.actionCreateComputer = QAction(self.trUtf8("我的电脑(&C)"), self)
self.actionCreateDocuments = QAction(self.trUtf8("我的文档(&D)"), self)
self.actionCreateMusic = QAction(self.trUtf8("我的音乐(&M)"), self)
self.actionCreatePictures = QAction(self.trUtf8("我的图片(&P)"), self)
self.actionCreateShortcut = QAction(self.trUtf8("创建快捷方式(&C)"), self)
self.actionCreateShortcut.setIcon(QIcon(":/images/new.png"))
self.actionCreateBookmark = QAction(self.trUtf8("创建网络链接(&B)"), self)
self.actionCreateBookmark.setIcon(QIcon(":/images/insert-link.png"))
self.actionRemoveShortcut = QAction(self.trUtf8("删除快捷方式(&R)"), self)
self.actionRemoveShortcut.setIcon(QIcon(":/images/delete.png"))
self.actionRenameShortcut = QAction(self.trUtf8("重命名(&N)"), self)
self.actionRenameShortcut.setIcon(QIcon(":/images/edit-rename.png"))
self.actionEditShortcut = QAction(self.trUtf8("编辑快捷方式(&E)"), self)
self.actionEditShortcut.setIcon(QIcon(":/images/edit.png"))
def makeConnections(self):
self.listView.customContextMenuRequested.connect(self.onQuickDesktopContextMenuRequest)
self.listView.activated.connect(self.runQuickDesktopShortcut)
self.actionCreateComputer.triggered.connect(self.createComputerShortcut)
self.actionCreateDocuments.triggered.connect(self.createDocumentsShortcut)
self.actionCreateMusic.triggered.connect(self.createMusicShortcut)
self.actionCreatePictures.triggered.connect(self.createPicturesShortcut)
self.actionCreateShortcut.triggered.connect(self.createShortcut)
self.actionCreateBookmark.triggered.connect(self.createBookmark)
self.actionEditShortcut.triggered.connect(self.editShortcut)
self.actionRemoveShortcut.triggered.connect(self.removeShortcut)
self.actionRenameShortcut.triggered.connect(self.renameShortcut)
def onQuickDesktopContextMenuRequest(self, pos):
index = self.listView.indexAt(pos)
self.listView.setCurrentIndex(index)
menu = QMenu()
menu.addAction(self.actionCreateShortcut)
menu.addAction(self.actionCreateBookmark)
menu2 = menu.addMenu(self.trUtf8("创建特殊快捷方式(&S)"))
if os.name == "nt":
menu2.addAction(self.actionCreateComputer)
menu2.addAction(self.actionCreateDocuments)
menu2.addAction(self.actionCreatePictures)
menu2.addAction(self.actionCreateMusic)
if index.isValid():
menu.addAction(self.actionRemoveShortcut)
if not self.quickDesktopModel.isSpecialShortcut(index):
menu.addAction(self.actionEditShortcut)
menu.addAction(self.actionRenameShortcut)
try:
getattr(menu, "exec")(QCursor.pos())
except AttributeError:
getattr(menu, "exec_")(QCursor.pos())
def createShortcut(self):
d = ShortcutDialog(self)
if self.window().runDialog(d.create) == QDialog.Accepted:
shortcut = d.getResult()
shortcut["id"] = str(uuid.uuid4())
self.quickDesktopModel.addShortcut(shortcut)
d.deleteLater()
def createBookmark(self):
d = BookmarkDialog(self)
if self.window().runDialog(d.create) == QDialog.Accepted:
shortcut = {
"id": str(uuid.uuid4()),
"icon": "",
"openwith": "",
"dir": "",
}
shortcut.update(d.getResult())
self.quickDesktopModel.addShortcut(shortcut)
d.deleteLater()
def createComputerShortcut(self):
shortcut = {
#.........这里部分代码省略.........