本文整理汇总了Python中PyQt4.QtGui.QListView.selectionModel方法的典型用法代码示例。如果您正苦于以下问题:Python QListView.selectionModel方法的具体用法?Python QListView.selectionModel怎么用?Python QListView.selectionModel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtGui.QListView
的用法示例。
在下文中一共展示了QListView.selectionModel方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: OWEditDomain
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [as 别名]
class OWEditDomain(widget.OWWidget):
name = "Edit Domain"
description = "Rename features and their values."
icon = "icons/EditDomain.svg"
priority = 3125
inputs = [("Data", Orange.data.Table, "set_data")]
outputs = [("Data", Orange.data.Table)]
settingsHandler = settings.DomainContextHandler()
domain_change_hints = settings.ContextSetting({})
selected_index = settings.ContextSetting({})
autocommit = settings.Setting(False)
def __init__(self):
super().__init__()
self.data = None
self.input_vars = ()
self._invalidated = False
box = gui.widgetBox(self.controlArea, "Domain Features")
self.domain_model = itemmodels.VariableListModel()
self.domain_view = QListView(
selectionMode=QListView.SingleSelection
)
self.domain_view.setModel(self.domain_model)
self.domain_view.selectionModel().selectionChanged.connect(
self._on_selection_changed)
box.layout().addWidget(self.domain_view)
box = gui.widgetBox(self.controlArea, "Reset")
gui.button(box, self, "Reset selected", callback=self.reset_selected)
gui.button(box, self, "Reset all", callback=self.reset_all)
gui.auto_commit(self.controlArea, self, "autocommit", "Commit",
"Commit on change is on")
box = gui.widgetBox(self.mainArea, "Edit")
self.editor_stack = QtGui.QStackedWidget()
self.editor_stack.addWidget(DiscreteVariableEditor())
self.editor_stack.addWidget(ContinuousVariableEditor())
self.editor_stack.addWidget(VariableEditor())
box.layout().addWidget(self.editor_stack)
@check_sql_input
def set_data(self, data):
"""Set input data set."""
self.closeContext()
self.clear()
self.data = data
if self.data is not None:
self._initialize()
self.openContext(self.data)
self._restore()
self.unconditional_commit()
def clear(self):
"""Clear the widget state."""
self.data = None
self.domain_model[:] = []
self.input_vars = []
self.domain_change_hints = {}
self.selected_index = -1
def reset_selected(self):
"""Reset the currently selected variable to its original state."""
ind = self.selected_var_index()
if ind >= 0:
var = self.input_vars[ind]
desc = variable_description(var)
if desc in self.domain_change_hints:
del self.domain_change_hints[desc]
self.domain_model[ind] = var
self.editor_stack.currentWidget().set_data(var)
self._invalidate()
def reset_all(self):
"""Reset all variables to their original state."""
self.domain_change_hints = {}
if self.data is not None:
# To invalidate stored hints
self.domain_model[:] = self.input_vars
itemmodels.select_row(self.domain_view, self.selected_index)
self._invalidate()
def selected_var_index(self):
"""Return the selected row in 'Domain Features' view."""
rows = self.domain_view.selectedIndexes()
assert len(rows) <= 1
return rows[0].row() if rows else -1
#.........这里部分代码省略.........
示例2: OWPySparkScript
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [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)
#.........这里部分代码省略.........
示例3: OWDiscretize
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [as 别名]
class OWDiscretize(widget.OWWidget):
name = "Discretize"
description = "Discretize the numeric data features."
icon = "icons/Discretize.svg"
inputs = [InputSignal("Data", Orange.data.Table, "set_data",
doc="Input data table")]
outputs = [OutputSignal("Data", Orange.data.Table,
doc="Table with discretized features")]
settingsHandler = settings.DomainContextHandler()
saved_var_states = settings.ContextSetting({})
default_method = settings.Setting(2)
default_k = settings.Setting(3)
autosend = settings.Setting(True)
#: Discretization methods
Default, Leave, MDL, EqualFreq, EqualWidth, Remove, Custom = range(7)
want_main_area = False
resizing_enabled = False
def __init__(self):
super().__init__()
#: input data
self.data = None
#: Current variable discretization state
self.var_state = {}
#: Saved variable discretization settings (context setting)
self.saved_var_states = {}
self.method = 0
self.k = 5
box = gui.vBox(self.controlArea, self.tr("Default Discretization"))
self.default_bbox = rbox = gui.radioButtons(
box, self, "default_method", callback=self._default_disc_changed)
options = self.options = [
self.tr("Default"),
self.tr("Leave numeric"),
self.tr("Entropy-MDL discretization"),
self.tr("Equal-frequency discretization"),
self.tr("Equal-width discretization"),
self.tr("Remove numeric variables")
]
for opt in options[1:5]:
gui.appendRadioButton(rbox, opt)
s = gui.hSlider(gui.indentedBox(rbox),
self, "default_k", minValue=2, maxValue=10,
label="Num. of intervals:",
callback=self._default_disc_changed)
s.setTracking(False)
gui.appendRadioButton(rbox, options[-1])
vlayout = QHBoxLayout()
box = gui.widgetBox(
self.controlArea, "Individual Attribute Settings",
orientation=vlayout, spacing=8
)
# List view with all attributes
self.varview = QListView(selectionMode=QListView.ExtendedSelection)
self.varview.setItemDelegate(DiscDelegate())
self.varmodel = itemmodels.VariableListModel()
self.varview.setModel(self.varmodel)
self.varview.selectionModel().selectionChanged.connect(
self._var_selection_changed
)
vlayout.addWidget(self.varview)
# Controls for individual attr settings
self.bbox = controlbox = gui.radioButtons(
box, self, "method", callback=self._disc_method_changed
)
vlayout.addWidget(controlbox)
for opt in options[:5]:
gui.appendRadioButton(controlbox, opt)
s = gui.hSlider(gui.indentedBox(controlbox),
self, "k", minValue=2, maxValue=10,
label="Num. of intervals:",
callback=self._disc_method_changed)
s.setTracking(False)
gui.appendRadioButton(controlbox, "Remove attribute")
gui.rubber(controlbox)
controlbox.setEnabled(False)
self.controlbox = controlbox
box = gui.auto_commit(
self.controlArea, self, "autosend", "Apply",
orientation=Qt.Horizontal,
#.........这里部分代码省略.........
示例4: SelectionSetsWidget
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [as 别名]
class SelectionSetsWidget(QFrame):
"""
Widget for managing multiple stored item selections
"""
selectionModified = Signal(bool)
def __init__(self, parent):
QFrame.__init__(self, parent)
self.setContentsMargins(0, 0, 0, 0)
layout = QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(1)
self._setNameLineEdit = QLineEdit(self)
layout.addWidget(self._setNameLineEdit)
self._setListView = QListView(self)
self._listModel = QStandardItemModel(self)
self._proxyModel = QSortFilterProxyModel(self)
self._proxyModel.setSourceModel(self._listModel)
self._setListView.setModel(self._proxyModel)
self._setListView.setItemDelegate(ListItemDelegate(self))
self._setNameLineEdit.textChanged.connect(
self._proxyModel.setFilterFixedString)
self._completer = QCompleter(self._listModel, self)
self._setNameLineEdit.setCompleter(self._completer)
self._listModel.itemChanged.connect(self._onSetNameChange)
layout.addWidget(self._setListView)
buttonLayout = QHBoxLayout()
self._addAction = QAction(
"+", self, toolTip="Add a new sort key")
self._updateAction = QAction(
"Update", self, toolTip="Update/save current selection")
self._removeAction = QAction(
"\u2212", self, toolTip="Remove selected sort key.")
self._addToolButton = QToolButton(self)
self._updateToolButton = QToolButton(self)
self._removeToolButton = QToolButton(self)
self._updateToolButton.setSizePolicy(
QSizePolicy.MinimumExpanding, QSizePolicy.Minimum)
self._addToolButton.setDefaultAction(self._addAction)
self._updateToolButton.setDefaultAction(self._updateAction)
self._removeToolButton.setDefaultAction(self._removeAction)
buttonLayout.addWidget(self._addToolButton)
buttonLayout.addWidget(self._updateToolButton)
buttonLayout.addWidget(self._removeToolButton)
layout.addLayout(buttonLayout)
self.setLayout(layout)
self._addAction.triggered.connect(self.addCurrentSelection)
self._updateAction.triggered.connect(self.updateSelectedSelection)
self._removeAction.triggered.connect(self.removeSelectedSelection)
self._setListView.selectionModel().selectionChanged.connect(
self._onListViewSelectionChanged)
self.selectionModel = None
self._selections = []
def sizeHint(self):
size = QFrame.sizeHint(self)
return QSize(size.width(), 200)
def _onSelectionChanged(self, selected, deselected):
self.setSelectionModified(True)
def _onListViewSelectionChanged(self, selected, deselected):
try:
index = self._setListView.selectedIndexes()[0]
except IndexError:
return
self.commitSelection(self._proxyModel.mapToSource(index).row())
def _onSetNameChange(self, item):
self.selections[item.row()].name = str(item.text())
def _setButtonStates(self, val):
self._updateToolButton.setEnabled(val)
def setSelectionModel(self, selectionModel):
if self.selectionModel:
self.selectionModel.selectionChanged.disconnect(
self._onSelectionChanged)
self.selectionModel = selectionModel
self.selectionModel.selectionChanged.connect(self._onSelectionChanged)
def addCurrentSelection(self):
item = self.addSelection(
SelectionByKey(self.selectionModel.selection(),
name="New selection",
key=(1, 2, 3, 10)))
index = self._proxyModel.mapFromSource(item.index())
#.........这里部分代码省略.........
示例5: DataTypeKeysWidget
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [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()
示例6: DataTypeKeysWidget
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [as 别名]
class DataTypeKeysWidget(QWidget):
dataTypeKeySelected = pyqtSignal(str)
def __init__(self):
QWidget.__init__(self)
layout = QVBoxLayout()
self.model = DataTypeKeysListModel()
self.filter_model = DataTypeProxyModel(self.model)
self.search_box = SearchBox()
self.search_box.filterChanged.connect(self.setSearchString)
layout.addWidget(self.search_box)
data_type_model = QStandardItemModel(0, 1)
item = QStandardItem("Select data types...")
data_type_model.appendRow(item)
self.__summary_item = QStandardItem("Summary")
self.__summary_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
self.__summary_item.setData(Qt.Checked, Qt.CheckStateRole)
data_type_model.appendRow(self.__summary_item)
self.__block_item = QStandardItem("Block")
self.__block_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
self.__block_item.setData(Qt.Checked, Qt.CheckStateRole)
data_type_model.appendRow(self.__block_item)
data_type_model.itemChanged.connect(self.onItemChanged)
combo = QComboBox()
combo.setModel(data_type_model)
layout.addWidget(combo)
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.addWidget(Legend("Default types", DataTypeKeysListModel.DEFAULT_DATA_TYPE))
layout.addWidget(Legend("Observations available", DataTypeKeysListModel.HAS_OBSERVATIONS))
self.setLayout(layout)
def onItemChanged(self, item):
assert isinstance(item, QStandardItem)
checked = item.checkState()==Qt.Checked
if item == self.__block_item:
self.filter_model.setShowBlockKeys(checked)
elif item == self.__summary_item:
self.filter_model.setShowSummaryKeys(checked)
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)
示例7: OWDiscretize
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [as 别名]
class OWDiscretize(widget.OWWidget):
name = "Discretize"
description = "Discretization of continuous attributes."
icon = "icons/Discretize.svg"
inputs = [{"name": "Data",
"type": Orange.data.Table,
"handler": "set_data",
"doc": "Input data table"}]
outputs = [{"name": "Data",
"type": Orange.data.Table,
"doc": "Table with discretized features"}]
settingsHandler = settings.DomainContextHandler()
saved_var_states = settings.ContextSetting({})
default_method = settings.Setting(0)
default_k = settings.Setting(5)
# Discretization methods
Default, Leave, MDL, EqualFreq, EqualWidth, Remove, Custom = range(7)
want_main_area = False
def __init__(self, parent=None):
super().__init__(parent)
#: input data
self.data = None
#: Current variable discretization state
self.var_state = {}
#: Saved variable discretization settings (context setting)
self.saved_var_states = {}
self.method = 0
self.k = 5
box = gui.widgetBox(
self.controlArea, self.tr("Default Discretization"))
rbox = gui.radioButtons(
box, self, "default_method", callback=self._default_disc_changed)
options = [
self.tr("Default"),
self.tr("Leave continuous"),
self.tr("Entropy-MDL discretization"),
self.tr("Equal-frequency discretization"),
self.tr("Equal-width discretization"),
self.tr("Remove continuous attributes")
]
for opt in options[1:5]:
gui.appendRadioButton(rbox, opt)
gui.hSlider(gui.indentedBox(rbox),
self, "default_k", minValue=2, maxValue=10,
label="Num. of intervals:",
callback=self._default_disc_changed)
gui.appendRadioButton(rbox, options[-1])
vlayout = QHBoxLayout()
box = gui.widgetBox(
self.controlArea, "Individual Attribute Settings",
orientation=vlayout
)
# List view with all attributes
self.varview = QListView(
selectionMode=QListView.ExtendedSelection
)
self.varview.setItemDelegate(DiscDelegate())
self.varmodel = itemmodels.VariableListModel()
self.varview.setModel(self.varmodel)
self.varview.selectionModel().selectionChanged.connect(
self._var_selection_changed
)
vlayout.addWidget(self.varview)
# Controls for individual attr settings
controlbox = gui.radioButtons(
box, self, "method", callback=self._disc_method_changed
)
vlayout.addWidget(controlbox)
for opt in options[:5]:
gui.appendRadioButton(controlbox, opt)
gui.hSlider(gui.indentedBox(controlbox),
self, "k", minValue=2, maxValue=10,
label="Num. of intervals:",
callback=self._disc_method_changed)
gui.appendRadioButton(controlbox, options[-1])
gui.rubber(controlbox)
controlbox.setEnabled(False)
self.controlbox = controlbox
#.........这里部分代码省略.........
示例8: OWQualityControl
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [as 别名]
class OWQualityControl(widget.OWWidget):
name = "Quality Control"
description = "Experiment quality control"
icon = "../widgets/icons/QualityControl.svg"
priority = 5000
inputs = [("Experiment Data", Orange.data.Table, "set_data")]
outputs = []
DISTANCE_FUNCTIONS = [("Distance from Pearson correlation",
dist_pcorr),
("Euclidean distance",
dist_eucl),
("Distance from Spearman correlation",
dist_spearman)]
settingsHandler = SetContextHandler()
split_by_labels = settings.ContextSetting({})
sort_by_labels = settings.ContextSetting({})
selected_distance_index = settings.Setting(0)
def __init__(self, parent=None):
super().__init__(parent)
## Attributes
self.data = None
self.distances = None
self.groups = None
self.unique_pos = None
self.base_group_index = 0
## GUI
box = gui.widgetBox(self.controlArea, "Info")
self.info_box = gui.widgetLabel(box, "\n")
## Separate By box
box = gui.widgetBox(self.controlArea, "Separate By")
self.split_by_model = itemmodels.PyListModel(parent=self)
self.split_by_view = QListView()
self.split_by_view.setSelectionMode(QListView.ExtendedSelection)
self.split_by_view.setModel(self.split_by_model)
box.layout().addWidget(self.split_by_view)
self.split_by_view.selectionModel().selectionChanged.connect(
self.on_split_key_changed)
## Sort By box
box = gui.widgetBox(self.controlArea, "Sort By")
self.sort_by_model = itemmodels.PyListModel(parent=self)
self.sort_by_view = QListView()
self.sort_by_view.setSelectionMode(QListView.ExtendedSelection)
self.sort_by_view.setModel(self.sort_by_model)
box.layout().addWidget(self.sort_by_view)
self.sort_by_view.selectionModel().selectionChanged.connect(
self.on_sort_key_changed)
## Distance box
box = gui.widgetBox(self.controlArea, "Distance Measure")
gui.comboBox(box, self, "selected_distance_index",
items=[name for name, _ in self.DISTANCE_FUNCTIONS],
callback=self.on_distance_measure_changed)
self.scene = QGraphicsScene()
self.scene_view = QGraphicsView(self.scene)
self.scene_view.setRenderHints(QPainter.Antialiasing)
self.scene_view.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
self.mainArea.layout().addWidget(self.scene_view)
self.scene_view.installEventFilter(self)
self._disable_updates = False
self._cached_distances = {}
self._base_index_hints = {}
self.main_widget = None
self.resize(800, 600)
def clear(self):
"""Clear the widget state."""
self.data = None
self.distances = None
self.groups = None
self.unique_pos = None
with disable_updates(self):
self.split_by_model[:] = []
self.sort_by_model[:] = []
self.main_widget = None
self.scene.clear()
self.info_box.setText("\n")
self._cached_distances = {}
def set_data(self, data=None):
"""Set input experiment data."""
self.closeContext()
self.clear()
#.........这里部分代码省略.........
示例9: Browser
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [as 别名]
class Browser(QWidget):
entrytype = type("EntryType", (object,), dict((v,k) for k,v in enumerate(
["directory", "playlist", "mediafile", "url"]
)))
col = type("BrowserColumns", (object,), dict((v,k) for k,v in enumerate(
["name", "last_modified", "entrytype", "uri"]
)))
@staticmethod
def columns():
return len(dict((k,v) for k,v in Browser.col.__dict__.items()
if not k.startswith("__")))
def __init__(self,app):
super(Browser,self).__init__()
self.mpd = app.mpd
self.ih = app.imagehelper
self.model = QStandardItemModel(0,self.columns(),self)
self.initGUI()
self.initActions()
def initGUI(self):
self.setWindowTitle(QApplication.applicationName())
layout = QVBoxLayout()
headerlayout = QHBoxLayout()
homeBtn = QToolButton()
homeBtn.setIcon(self.ih.homeButton)
homeBtn.setFixedSize(64,64)
homeBtn.clicked.connect(self.home)
headerlayout.addWidget(homeBtn)
label = QLabel("<b>Location</b>")
label.setMargin(10)
label.setFixedSize(label.sizeHint())
headerlayout.addWidget(label)
self.currentLocation = ClickableLabel("")
self.currentLocation.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
self.currentLocation.setWordWrap(True)
self.currentLocation.setFixedSize(400,64)
self.currentLocation.clicked.connect(self.back)
headerlayout.addWidget(self.currentLocation)
headerlayout.addStretch()
layout.addLayout(headerlayout)
self.view = QListView()
self.view.setSelectionMode( QAbstractItemView.SingleSelection)
self.view.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.view.setContextMenuPolicy(Qt.CustomContextMenu)
self.view.customContextMenuRequested.connect(self.contextMenu)
self.view.setModel(self.model)
self.view.setModelColumn(0)
#self.view.doubleClicked.connect(self.doubleClicked)
self.view.activated.connect(self.activated)
layout.addWidget(self.view)
self.setLayout(layout)
def initActions(self):
self.actionAdd = QAction("Add", self)
self.actionAddPlay = QAction("Add and Play", self)
self.actionInsert = QAction("Insert", self)
self.actionReplace = QAction("Replace", self)
self.actionReplacePlay = QAction("Replace and Play", self)
self.actionUpdate = QAction("Update", self)
self.actionUpdateAll = QAction("Update all", self)
# playlist actions
self.actionPlsRename = QAction("Rename", self)
self.actionPlsDelete = QAction("Delete", self)
def contextMenu(self,pos):
if self.model.rowCount() == 0: return
mi = self.view.selectionModel().currentIndex()
if not mi.isValid(): return
uri = self.model.item(mi.row(),self.col.uri).text()
entrytype = int(self.model.item(mi.row(),self.col.entrytype).text())
addfunc = None
if entrytype != self.entrytype.playlist:
addfunc = self.mpd.add
else:
addfunc = self.mpd.load
popup = QMenu()
popup.addAction(self.actionAdd)
popup.addAction(self.actionAddPlay)
if entrytype == self.entrytype.mediafile or \
entrytype == self.entrytype.url:
popup.addAction(self.actionInsert)
popup.addAction(self.actionReplace)
popup.addAction(self.actionReplacePlay)
if entrytype == self.entrytype.playlist:
popup.addAction(self.actionPlsRename)
popup.addAction(self.actionPlsDelete)
else:
popup.addAction(self.actionUpdate)
popup.addAction(self.actionUpdateAll)
action = popup.exec_(self.mapToGlobal(pos))
status = self.mpd.status()
#.........这里部分代码省略.........
示例10: OWGenotypeDistances
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [as 别名]
#.........这里部分代码省略.........
def set_data(self, data=None):
"""Set the input data table.
"""
self.closeContext()
self.clear()
self.error(0)
self.warning(0)
if data and not self.get_suitable_keys(data):
self.error(0, "Data has no suitable attribute labels.")
data = None
self.data = data
if data:
self.info_box.setText("{0} genes\n{1} experiments"
.format(len(data), len(data.domain)))
self.update_control()
self.split_data()
else:
self.separate_view.setModel(itemmodels.PyListModel([]))
self.relevant_view.setModel(itemmodels.PyListModel([]))
self.groups_scroll_area.setWidget(QWidget())
self.info_box.setText("No data on input.\n")
self.commit()
def update_control(self):
"""Update the control area of the widget. Populate the list
views with keys from attribute labels.
"""
keys = self.get_suitable_keys(self.data)
model = itemmodels.PyListModel(keys)
self.separate_view.setModel(model)
self.separate_view.selectionModel().selectionChanged.connect(
self.on_separate_key_changed)
model = itemmodels.PyListModel(keys)
self.relevant_view.setModel(model)
self.relevant_view.selectionModel().selectionChanged.connect(
self.on_relevant_key_changed)
self.openContext(keys)
# Get the selected keys from the open context
separate_keys = self.separate_keys
relevant_keys = self.relevant_keys
def select(model, selection_model, selected_items):
all_items = list(model)
try:
indices = [all_items.index(item) for item in selected_items]
except:
indices = []
selection = QItemSelection()
for ind in indices:
index = model.index(ind)
selection.select(index, index)
selection_model.select(selection, QItemSelectionModel.Select)
self._disable_updates = True
try:
select(self.relevant_view.model(),
self.relevant_view.selectionModel(),
relevant_keys)
示例11: OWSpiralogram
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [as 别名]
class OWSpiralogram(widget.OWWidget):
name = 'Spiralogram'
description = "Visualize time series' periodicity in a spiral heatmap."
icon = 'icons/Spiralogram.svg'
priority = 120
inputs = [("Time series", Table, 'set_data')]
outputs = [("Time series", Timeseries)]
ax1 = settings.Setting('months of year')
ax2 = settings.Setting('years')
agg_attr = settings.Setting([])
agg_func = settings.Setting(0)
def __init__(self):
self.data = None
self.indices = []
box = gui.vBox(self.controlArea, 'Axes')
self.combo_ax2 = gui.comboBox(
box, self, 'ax2', label='Y axis:', callback=self.replot,
sendSelectedValue=True, orientation='horizontal')
self.combo_ax1 = gui.comboBox(
box, self, 'ax1', label='Radial:', callback=self.replot,
sendSelectedValue=True, orientation='horizontal')
box = gui.vBox(self.controlArea, 'Aggregation')
self.combo_func = gui.comboBox(
box, self, 'agg_func', label='Function:', orientation='horizontal',
callback=self.replot)
func_model = ListModel(AGG_FUNCTIONS, parent=self)
self.combo_func.setModel(func_model)
self.attrlist_model = VariableListModel(parent=self)
self.attrlist = QListView(selectionMode=QListView.ExtendedSelection)
self.attrlist.setModel(self.attrlist_model)
self.attrlist.selectionModel().selectionChanged.connect(
self.attrlist_selectionChanged)
box.layout().addWidget(self.attrlist)
gui.rubber(self.controlArea)
self.chart = chart = Spiralogram(self,
selection_callback=self.on_selection)
self.mainArea.layout().addWidget(chart)
def attrlist_selectionChanged(self):
self.agg_attr = [self.attrlist_model[i.row()]
for i in self.attrlist.selectionModel().selectedIndexes()]
self.replot()
def set_data(self, data):
self.data = data = None if data is None else Timeseries.from_data_table(data)
def init_combos():
for combo in (self.combo_ax1, self.combo_ax2):
combo.clear()
self.attrlist_model[:] = []
for i in Spiralogram.AxesCategories:
for combo in (self.combo_ax1, self.combo_ax2):
combo.addItem(_enum_str(i))
for var in data.domain if data is not None else []:
if (var.is_primitive() and
(var is not data.time_variable or
isinstance(var, TimeVariable) and data.time_delta is None)):
self.attrlist_model.append(var)
if var.is_discrete:
for combo in (self.combo_ax1, self.combo_ax2):
combo.addItem(gui.attributeIconDict[var], var.name)
init_combos()
self.chart.clear()
if data is None:
self.commit()
return
self.ax1 = 'months of year'
self.ax2 = 'years'
self.replot()
def replot(self):
vars = self.agg_attr
func = AGG_FUNCTIONS[self.agg_func]
# TODO test discrete
if any(var.is_discrete for var in vars) and func != Mode:
self.combo_func.setCurrentIndex(AGG_FUNCTIONS.index(Mode))
return
try:
ax1 = Spiralogram.AxesCategories[_enum_str(self.ax1, True)]
except KeyError:
ax1 = self.data.domain[self.ax1]
# TODO: Allow having only a sinle (i.e. radial) axis
try:
ax2 = Spiralogram.AxesCategories[_enum_str(self.ax2, True)]
except KeyError:
ax2 = self.data.domain[self.ax2]
self.chart.setSeries(self.data, vars, ax1, ax2, func)
def on_selection(self, indices):
self.indices = self.chart.selection_indices(indices)
self.commit()
def commit(self):
self.send('Time series', self.data[self.indices] if self.data else None)
示例12: OWPythonScript
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [as 别名]
class OWPythonScript(OWWidget):
settingsList = ["libraryListSource", "currentScriptIndex",
"splitterState", "auto_execute"]
def __init__(self, parent=None, signalManager=None):
OWWidget.__init__(self, parent, signalManager, 'Python Script')
self.inputs = [("in_data", Orange.data.Table, self.setExampleTable,
Default),
("in_distance", Orange.misc.SymMatrix,
self.setDistanceMatrix, Default),
("in_learner", Orange.core.Learner, self.setLearner,
Default),
("in_classifier", Orange.core.Classifier,
self.setClassifier, Default),
("in_object", object, self.setObject)]
self.outputs = [("out_data", Orange.data.Table),
("out_distance", Orange.misc.SymMatrix),
("out_learner", Orange.core.Learner),
("out_classifier", Orange.core.Classifier, Dynamic),
("out_object", object, Dynamic)]
self.in_data = None
self.in_distance = None
self.in_learner = None
self.in_classifier = None
self.in_object = None
self.auto_execute = False
self.libraryListSource = [Script("Hello world",
"print 'Hello world'\n")]
self.currentScriptIndex = 0
self.splitterState = None
self.loadSettings()
for s in self.libraryListSource:
s.flags = 0
self._cachedDocuments = {}
self.infoBox = OWGUI.widgetBox(self.controlArea, 'Info')
OWGUI.label(
self.infoBox, self,
"<p>Execute python script.</p><p>Input variables:<ul><li> " +
"<li>".join(t[0] for t in self.inputs) +
"</ul></p><p>Output variables:<ul><li>" +
"<li>".join(t[0] for t in self.outputs) +
"</ul></p>"
)
self.libraryList = PyListModel(
[], self,
flags=Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable
)
self.libraryList.wrap(self.libraryListSource)
self.controlBox = OWGUI.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 = 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))
#.........这里部分代码省略.........
示例13: OrderSelectorView
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [as 别名]
#.........这里部分代码省略.........
self.pushButton_up_arrow.setMinimumSize(QSize(50,50))
self.pushButton_up_arrow.setMaximumSize(QSize(50,50))
self.pushButton_up_arrow.setIcon(QIcon(':/up_arrow.png'))
self.pushButton_up_arrow.setIconSize(QSize(50,50))
self.pushButton_up_arrow.setText('')
self.verticalLayout_up_down.addWidget(self.pushButton_up_arrow)
self.pushButton_down_arrow = QPushButton(parentWidget)
sizePolicy.setHeightForWidth(
self.pushButton_down_arrow.sizePolicy().hasHeightForWidth())
self.pushButton_down_arrow.setSizePolicy(sizePolicy)
self.pushButton_down_arrow.setMinimumSize(QSize(50,50))
self.pushButton_down_arrow.setMaximumSize(QSize(50,50))
self.pushButton_down_arrow.setIcon(QIcon(':/down_arrow.png'))
self.pushButton_down_arrow.setIconSize(QSize(50,50))
self.pushButton_down_arrow.setText('')
self.verticalLayout_up_down.addWidget(self.pushButton_down_arrow)
spacerItem = QSpacerItem(20,178,QSizePolicy.Minimum,QSizePolicy.Expanding)
self.verticalLayout_up_down.addItem(spacerItem)
self.gridLayout.addLayout(self.verticalLayout_up_down, 0, 5, 1, 1)
self.listView_NotSelected.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.listView_Selected.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.listView_NotSelected.setModel(self.model.model_NotSelected)
self.listView_Selected.setModel(self.model.model_Selected)
#----------------------------------------------------------------------
def on_right_arrow_press(self):
""""""
NSMod = self.listView_NotSelected.model()
NSSelMod = self.listView_NotSelected.selectionModel()
SMod = self.listView_Selected.model()
SSelMod = self.listView_Selected.selectionModel()
mod_ind_list = NSSelMod.selectedRows(0)
if mod_ind_list == []:
return
else:
SSelMod.clearSelection()
while mod_ind_list != []:
mod_ind = mod_ind_list[0]
item = NSMod.itemFromIndex(mod_ind)
new_item = item.clone()
SMod.appendRow(new_item)
SSelMod.select(SMod.indexFromItem(new_item),
QItemSelectionModel.Select)
NSMod.removeRow(mod_ind.row())
mod_ind_list = NSSelMod.selectedRows(0)
#----------------------------------------------------------------------
def on_left_arrow_press(self):
""""""
SMod = self.listView_Selected.model()
SSelMod = self.listView_Selected.selectionModel()
NSMod = self.listView_NotSelected.model()
NSSelMod = self.listView_NotSelected.selectionModel()
mod_ind_list = SSelMod.selectedRows(0)
示例14: OWMoleculeVisualizer
# 需要导入模块: from PyQt4.QtGui import QListView [as 别名]
# 或者: from PyQt4.QtGui.QListView import selectionModel [as 别名]
class OWMoleculeVisualizer(OWWidget):
settingsList = ["colorFragmets", "showFragments"]
contextHandlers = {
"": DomainContextHandler(
"",
[ContextField("selected_title_indices"),
ContextField("moleculeTitleAttributeList",
(DomainContextHandler.List +
DomainContextHandler.SelectedRequired +
DomainContextHandler.IncludeMetaAttributes),
selected="selectedMoleculeTitleAttrs"),
ContextField("smiles_var",
DomainContextHandler.Required +
DomainContextHandler.IncludeMetaAttributes)],
maxAttributesToPickle=1000)
}
def __init__(self, parent=None, signalManager=None,
title="Molecule visualizer"):
super(OWMoleculeVisualizer, self).__init__(parent, signalManager, title)
self.colorFragments = 1
self.showFragments = 0
self.selectedFragment = ""
self.moleculeSmiles = []
self.fragmentSmiles = []
self.defFragmentSmiles = []
self.smiles_var = 0
self.moleculeTitleAttr = 0
self.moleculeTitleAttributeList = []
self.selectedMoleculeTitleAttrs = []
self.fragmentSmilesAttr = 0
self.imageSize = 200
self.numColumns = 4
self.commitOnChange = 0
## GUI
box = OWGUI.widgetBox(self.controlArea, "Info", addSpace=True)
self.infoLabel = OWGUI.label(box, self, "Chemicals:")
box = OWGUI.radioButtonsInBox(
self.controlArea, self, "showFragments",
["Show molecules", "Show fragments"], "Show",
callback=self.updateitems
)
self.showFragmentsRadioButton = box.buttons[-1]
self.markFragmentsCheckBox = OWGUI.checkBox(
box, self, "colorFragments", "Mark fragments",
callback=self._update
)
box.setSizePolicy(
QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum))
OWGUI.separator(self.controlArea)
self.moleculeSmilesCombo = OWGUI.comboBox(
self.controlArea, self, "smiles_var",
"Molecule SMILES Attribute",
callback=self.updateitems
)
self.moleculeSmilesCombo.box.setSizePolicy(
QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)
)
self.smiles_var_model = VariableListModel(parent=self)
self.moleculeSmilesCombo.setModel(self.smiles_var_model)
OWGUI.separator(self.controlArea)
box = OWGUI.widgetBox(self.controlArea, "Molecule Title Attributes",
addSpace=True)
self.title_var_view = QListView(
selectionMode=QListView.ExtendedSelection
)
self.title_var_model = VariableListModel(parent=self)
self.title_var_view.setModel(self.title_var_model)
self.title_var_view.selectionModel().selectionChanged.connect(
self._title_selection_changed
)
box.layout().addWidget(self.title_var_view)
OWGUI.separator(self.controlArea)
self.fragmentSmilesCombo = OWGUI.comboBox(
self.controlArea, self, "fragmentSmilesAttr",
"Fragment SMILES Attribute",
callback=self.updateFragmentsListBox
)
self.fragmentSmilesCombo.setModel(VariableListModel(parent=self))
self.fragmentSmilesCombo.box.setSizePolicy(
QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)
)
OWGUI.separator(self.controlArea)
box = OWGUI.spin(self.controlArea, self, "imageSize", 50, 500, 10,
box="Image Size", callback=self._image_size_changed)
box.setSizePolicy(
QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum))
OWGUI.separator(self.controlArea)
box = OWGUI.widgetBox(self.controlArea, "Selection", addSpace=True)
#.........这里部分代码省略.........