本文整理汇总了Python中PyQt5.QtWidgets.QTableView.selectionModel方法的典型用法代码示例。如果您正苦于以下问题:Python QTableView.selectionModel方法的具体用法?Python QTableView.selectionModel怎么用?Python QTableView.selectionModel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QTableView
的用法示例。
在下文中一共展示了QTableView.selectionModel方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ZoteroTableWidget
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import selectionModel [as 别名]
class ZoteroTableWidget(QWidget):
def __init__(self, settings, directory, check_id_fct, annotations_path, parent=None):
super().__init__(parent)
# FIXME Delayed refactoring of check_id_fct and annotations_path.
# Variables section.
library_id = settings["libraryID"]
library_type = settings["libraryType"]
api_key = settings["apiKey"]
self._zotero = ZoteroWrap(library_id, library_type, api_key, directory)
# Widgets section.
model = ZoteroTableModel(self._zotero, check_id_fct, annotations_path)
model.load()
proxy_model = QSortFilterProxyModel()
proxy_model.setSourceModel(model)
proxy_model.setDynamicSortFilter(True)
proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
proxy_model.setFilterKeyColumn(-1) # NB: All columns.
self.view = QTableView(self)
self.view.setModel(proxy_model)
self.view.setCornerButtonEnabled(False)
self.view.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.view.setSelectionBehavior(QAbstractItemView.SelectRows)
self.view.setSelectionMode(QAbstractItemView.SingleSelection)
# NB: Triggers a call to sortByColumn() which sorts by the first column.
self.view.setSortingEnabled(True)
self.view.setWordWrap(False)
self.view.verticalHeader().hide()
self.filter_edit = FilterEdit(self.view)
# NB: The thread does not begin executing until start() is called.
self.refresh_thread = ZoteroRefreshThread(model, self)
# Layouts section.
header_layout = QFormLayout()
header_layout.addRow("Filter:", self.filter_edit)
header_layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
utils.configure_form_layout(header_layout)
main_layout = QVBoxLayout()
main_layout.addLayout(header_layout)
main_layout.addWidget(self.view)
self.setLayout(main_layout)
# Signals section.
self.filter_edit.textChanged.connect(proxy_model.setFilterFixedString)
self.refresh_thread.started.connect(self.refresh_started)
self.refresh_thread.finished.connect(self.refresh_finished)
# def __del__(self):
# # FIXME Delayed refactoring. Not called when application is closed. Incorrect parent use?
# # NB: Exiting the program when another thread is still busy is a programming error.
# # NB: Call QThread::quit() if the thread has an event loop.
# print("DEBUG: ZoteroTableWidget.__del__()")
# # TODO Display an information dialog.
# self.refresh_thread.wait()
# print("DEBUG: ZoteroRefreshThread.wait() returned")
# Slots section.
@pyqtSlot()
def refresh_database(self):
"""Start the thread refreshing the Zotero data.
If the thread is already running, it is not restarted.
"""
self.refresh_thread.start()
@pyqtSlot()
def refresh_started(self):
"""Disable the Zotero widget when the thread refreshing its data runs.
Disable handling of keyboard/mouse events to ensure a thread-safe refresh.
"""
# TODO Display an information on top of the disabled widget.
self.setDisabled(True)
@pyqtSlot()
def refresh_finished(self):
"""Enable the Zotero widget when the thread refreshing its data finishes.
Reset the selection model of the view in case of new/deleted references.
Enable again the handling of keyboard/mouse events.
"""
self.view.selectionModel().reset()
self.setEnabled(True)
@pyqtSlot()
def add_reference(self):
"""Display the form for and handle the creation of a new reference."""
dialog = ZoteroReferenceDialog(self._zotero.reference_templates, self)
#.........这里部分代码省略.........
示例2: RelationDialog
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import selectionModel [as 别名]
class RelationDialog(QDialog):
""" Base class for creator and edit relation """
def __init__(self, parent=None):
QDialog.__init__(self, parent)
self.setWindowTitle(self.tr("Relation Editor"))
# Data
self.data = None
self.resize(700, 500)
box = QVBoxLayout(self)
# Relation name
self.relation_name = QLineEdit()
self.relation_name.setVisible(False)
box.addWidget(self.relation_name)
# Buttons
box_btns = QHBoxLayout()
add_tuple_btn = QPushButton(self.tr("Add Tuple"))
box_btns.addWidget(add_tuple_btn)
delete_tuple_btn = QPushButton(self.tr("Delete Tuple"))
box_btns.addWidget(delete_tuple_btn)
add_column_btn = QPushButton(self.tr("Add Column"))
box_btns.addWidget(add_column_btn)
delete_column_btn = QPushButton(self.tr("Delete Column"))
box_btns.addWidget(delete_column_btn)
box.addLayout(box_btns)
# Table
self.table = QTableView()
self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.table.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
self.table.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
# Editable header
header = custom_table.Header()
self.table.setHorizontalHeader(header)
box.addWidget(self.table)
# Save and cancel button
hbox = QHBoxLayout()
hbox.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding))
save_btn = QPushButton(self.tr("Ok"))
hbox.addWidget(save_btn)
cancel_btn = QPushButton(self.tr("Cancel"))
hbox.addWidget(cancel_btn)
box.addLayout(hbox)
# Connections
save_btn.clicked.connect(self.save)
cancel_btn.clicked.connect(self.close)
add_tuple_btn.clicked.connect(self.__add_tuple)
delete_tuple_btn.clicked.connect(self.__delete_tuple)
add_column_btn.clicked.connect(self.__add_column)
delete_column_btn.clicked.connect(self.__delete_column)
def setup_table(self, rela):
raise NotImplementedError
def save(self):
raise NotImplementedError
def __add_tuple(self):
model = self.table.model()
model.insertRow(model.rowCount())
def __delete_tuple(self):
model = self.table.model()
selection = self.table.selectionModel()
if selection.hasSelection():
r = QMessageBox.question(
self,
self.tr("Confirm tuple delete"),
self.tr("Are you sure you want " "to delete the selected " "tuple(s)?"),
QMessageBox.Yes | QMessageBox.No,
)
if r == QMessageBox.Yes:
selection = selection.selection()
rows = set([index.row() for index in selection.indexes()])
rows = sorted(list(rows))
previous = -1
i = len(rows) - 1
while i >= 0:
current = rows[i]
if current != previous:
model.removeRows(current, 1)
i -= 1
def __add_column(self):
model = self.table.model()
model.insertColumn(model.columnCount())
def __delete_column(self):
model = self.table.model()
if model.columnCount() >= 2:
model.takeColumn(model.columnCount() - 1)
示例3: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import selectionModel [as 别名]
class MainWindow(QMainWindow):
def __init__(self, data):
super().__init__()
self.resize(400, 600)
self.setWindowTitle('Logger Skeleton')
self.statusBar().showMessage("Ready", 2000)
# Make widgets ####################################
self.tabs = QTabWidget(self)
self.setCentralWidget(self.tabs)
# Add tabs
self.table_tab = QWidget(self)
self.stats_tab = QWidget(self)
self.tabs.addTab(self.table_tab, "Table")
self.tabs.addTab(self.stats_tab, "Stats")
# Table tab ###########################################################
self.table_view = QTableView(self.table_tab)
self.text_edit = QPlainTextEdit()
self.btn_add_row = QPushButton("Add a row")
#self.btn_remove_row = QPushButton("Remove selected rows")
table_tab_vbox = QVBoxLayout()
table_tab_vbox.addWidget(self.table_view)
table_tab_vbox.addWidget(self.text_edit)
table_tab_vbox.addWidget(self.btn_add_row)
#table_tab_vbox.addWidget(self.btn_remove_row)
self.table_tab.setLayout(table_tab_vbox)
# Set model #######################################
my_model = DataQtModel(data, parent=self) # TODO: right use of "parent" ?
# Proxy model #####################################
proxy_model = QSortFilterProxyModel(parent=self) # TODO: right use of "parent" ?
proxy_model.setSourceModel(my_model)
self.table_view.setModel(proxy_model)
#self.table_view.setModel(my_model)
# Set the view ####################################
self.table_view.setSelectionBehavior(QAbstractItemView.SelectRows) # Select the full row when a cell is selected (See http://doc.qt.io/qt-5/qabstractitemview.html#selectionBehavior-prop )
#self.table_view.setSelectionMode(QAbstractItemView.SingleSelection) # Set selection mode. See http://doc.qt.io/qt-5/qabstractitemview.html#selectionMode-prop
self.table_view.setAlternatingRowColors(True)
self.table_view.setSortingEnabled(True)
self.table_view.setColumnWidth(0, 200) # TODO: automatically get the best width
self.table_view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # https://stackoverflow.com/q/17535563
self.table_view.setColumnHidden(COMMENT_COLUMN_INDEX, True)
delegate = Delegate()
self.table_view.setItemDelegate(delegate)
# Set key shortcut ################################
# see https://stackoverflow.com/a/17631703 and http://doc.qt.io/qt-5/qaction.html#details
# Add row action
add_action = QAction(self.table_view)
add_action.setShortcut(Qt.CTRL | Qt.Key_N)
add_action.triggered.connect(self.add_row_btn_callback)
self.table_view.addAction(add_action)
# Delete action
del_action = QAction(self.table_view)
del_action.setShortcut(Qt.Key_Delete)
del_action.triggered.connect(self.remove_row_callback)
self.table_view.addAction(del_action)
# Set QDataWidgetMapper ###########################
self.mapper = QDataWidgetMapper()
self.mapper.setModel(proxy_model) # WARNING: do not use `my_model` here otherwise the index mapping will be wrong!
self.mapper.addMapping(self.text_edit, COMMENT_COLUMN_INDEX)
self.mapper.toFirst() # TODO: is it a good idea ?
self.table_view.selectionModel().selectionChanged.connect(self.update_selection)
# Set slots #######################################
self.btn_add_row.clicked.connect(self.add_row_btn_callback)
#self.btn_remove_row.clicked.connect(self.remove_row_callback)
#self.table_view.setColumnHidden(1, True)
#.........这里部分代码省略.........
示例4: ParamModWgt
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import selectionModel [as 别名]
class ParamModWgt(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.main_window = parent
self.buildRequiredTagsGB()
# Widgets
self.newParamBtn = QPushButton("New")
self.deleteParamBtn = QPushButton("Delete")
self.paramSaveAnnotBtn = QPushButton("Save")
buttonWidget = QWidget(self)
self.existingParamsGB = QGroupBox("Existing parameters", self)
self.paramListTblWdg = QTableView()
self.paramListModel = ParameterListModel(parent=self)
self.paramListTblWdg.setSelectionBehavior(QAbstractItemView.SelectRows)
self.paramListTblWdg.setSelectionMode(QAbstractItemView.SingleSelection)
self.paramListTblWdg.setModel(self.paramListModel)
self.paramListTblWdg.setColumnWidth(0, 150)
self.paramListTblWdg.setColumnWidth(1, 350)
self.relationWgt = ParamRelationWgt(parent)
self.newParamsGB = QGroupBox("Parameter details", self)
self.resultTypeCbo = QComboBox(self)
self.isExpProp = QCheckBox("is an experimental property", self)
self.resultTypeCbo.addItems(["point value", "function", "numerical trace"])
self.singleValueParamWgt = ParamValueWgt(parent)
self.functionParamWgt = ParamFunctionWgt(parent)
self.traceParamWgt = ParamTraceWgt(parent)
self.functionParamWgt.mainWgt = self
self.paramModStack = QStackedWidget(self)
self.paramModStack.addWidget(self.singleValueParamWgt)
self.paramModStack.addWidget(self.functionParamWgt)
self.paramModStack.addWidget(self.traceParamWgt)
# Signals
selectionModel = self.paramListTblWdg.selectionModel()
selectionModel.selectionChanged.connect(self.selectedParameterChanged)
self.newParamBtn.clicked.connect(self.newParameter)
self.deleteParamBtn.clicked.connect(self.deleteParameter)
self.paramSaveAnnotBtn.clicked.connect(self.saveParameter)
self.resultTypeCbo.currentIndexChanged.connect(self.paramModStack.setCurrentIndex)
self.singleValueParamWgt.paramTypeSelected.connect(self.newParamTypeSelected)
self.functionParamWgt.paramTypeSelected.connect(self.newParamTypeSelected)
self.traceParamWgt.paramTypeSelected.connect(self.newParamTypeSelected)
# Layout
buttonLayout = QVBoxLayout(buttonWidget)
buttonLayout.addWidget(self.paramSaveAnnotBtn)
buttonLayout.addWidget(self.deleteParamBtn)
buttonLayout.addWidget(self.newParamBtn)
existGrid = QHBoxLayout(self.existingParamsGB)
existGrid.addWidget(buttonWidget)
existGrid.addWidget(self.paramListTblWdg)
newGrid = QGridLayout(self.newParamsGB)
newGrid.addWidget(QLabel("Result type"), 0, 0)
newGrid.addWidget(self.resultTypeCbo, 0, 1)
newGrid.addWidget(self.isExpProp, 0, 2)
newGrid.addWidget(self.paramModStack, 1, 0, 1, 3)
newGrid.addWidget(self.relationWgt, 1, 3)
layout = QVBoxLayout(self)
self.rootLayout = QSplitter(Qt.Vertical, self)
self.rootLayout.setOrientation(Qt.Vertical)
self.rootLayout.addWidget(self.existingParamsGB)
self.rootLayout.addWidget(self.newParamsGB)
self.rootLayout.addWidget(self.requireTagGB)
layout.addWidget(self.rootLayout)
# Initial behavior
self.newParamBtn.setEnabled(True)
self.deleteParamBtn.setEnabled(False)
self.paramSaveAnnotBtn.setEnabled(False)
self.additionMode = False
self.newParamsGB.setEnabled(False)
def setRootLayoutSizes(self, sizes):
self.rootLayout.setSizes(sizes)
def viewParameter(self, parameter):
row = -1
for row, param in enumerate(self.paramListModel.parameterList):
if param.id == parameter.id:
break
assert(row > -1)
self.paramListTblWdg.selectRow(row)
#.........这里部分代码省略.........
示例5: QApplication
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import selectionModel [as 别名]
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QWidget()
table_view1 = QTableView()
table_view2 = QTableView()
my_model = MyModel(None)
table_view1.setModel(my_model)
table_view2.setModel(my_model)
# http://doc.qt.io/qt-5/model-view-programming.html#sharing-selections-among-views
table_view2.setSelectionModel(table_view1.selectionModel()) # <- Share the SelectionModel
# Set the layout
vbox = QVBoxLayout()
vbox.addWidget(table_view1)
vbox.addWidget(table_view2)
window.setLayout(vbox)
# Show
window.show()
# The mainloop of the application. The event handling starts from this point.
# The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead.
示例6: QVariant
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import selectionModel [as 别名]
return QVariant()
def print_selection(new_selection, old_selection):
old_selection_indexes = [((index.row(), index.column()), index.data(Qt.DisplayRole)) for index in old_selection.indexes()]
new_selection_indexes = [((index.row(), index.column()), index.data(Qt.DisplayRole)) for index in new_selection.indexes()]
print(old_selection_indexes, " -> ", new_selection_indexes)
if __name__ == '__main__':
app = QApplication(sys.argv)
table_view = QTableView()
my_model = MyModel(None)
table_view.setModel(my_model)
# Bind selection to the print_selection function (must be after the model setup)
selection_model = table_view.selectionModel()
selection_model.selectionChanged.connect(print_selection)
table_view.show()
# The mainloop of the application. The event handling starts from this point.
# The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead.
exit_code = app.exec_()
# The sys.exit() method ensures a clean exit.
# The environment will be informed, how the application ended.
sys.exit(exit_code)
示例7: ExportFrame
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import selectionModel [as 别名]
class ExportFrame(QFrame):
def get_existing_resync_file(self, resync_file):
# get the existing resync_file as file URI.
# return 'file://'+self.config.get_cfg_resync_dir()+'/'+resync_file
p = PurePath(self.config.cfg_resync_dir(), resync_file)
return p.as_uri()
def __init__(self, parent):
super().__init__(parent)
self.logger = logging.getLogger(__name__)
self.config = Configuration()
self.filenames = []
self.data = ""
# left part of frame
header_left = [_("Relative Path"), _("Name"), _("Size"), _("Date Modified")]
self.file_model = FileTableModel(self, header_left, [])
self.file_view = QTableView()
self.file_view.setModel(self.file_model)
self.file_view.setSortingEnabled(True)
self.file_view.setAlternatingRowColors(True)
self.file_view.setShowGrid(False)
# adjustments
self.file_view.verticalHeader().setDefaultSectionSize(22)
# self.file_view.horizontalHeader().setDefaultSectionSize(self.file_view.width()/len(header))
# self.file_view.horizontalHeader().setStretchLastSection(True)
self.file_view.setSelectionMode(QAbstractItemView.SingleSelection)
self.file_view.setSelectionBehavior(QAbstractItemView.SelectRows)
self.file_view.doubleClicked.connect(self.file_view_doubleclicked)
# self.file_view.clicked.connect(self.file_view_clicked)
self.file_view.selectionModel().selectionChanged.connect(self.file_view_selection_changed)
# self.file_view.setContextMenuPolicy(Qt.CustomContextMenu)
# self.file_view.customContextMenuRequested.connect(self.file_view_context_menu_requested)
# self.lb_nsfc = QLabel("")
self.lb_path = QLabel("")
self.lb_path.setFont(QFont("SansSerif", 10))
self.pb_select = QPushButton(_("Select"))
self.pb_select.clicked.connect(self.show_explorer)
# right part of frame
header_right = [_("Set Name"), _("Files"), _("New Files"), _("Update Files"), _("Unchanged Files")]
self.overview_model = OverviewTableModel(self, header_right, [])
self.overview = QTableView()
self.overview.setModel(self.overview_model)
self.overview.setAlternatingRowColors(True)
self.overview.setShowGrid(False)
self.overview.verticalHeader().setDefaultSectionSize(22)
self.pb_publish = QPushButton(_("Publish"))
self.pb_publish.clicked.connect(self.pb_publish_clicked)
self.pb_zip = QPushButton(_("Create Zip"))
self.pb_zip.clicked.connect(self.pb_zip_clicked)
self.__init_ui__()
def __init_ui__(self):
vbox = QVBoxLayout()
splitter = QSplitter()
splitter.addWidget(self.file_view)
splitter.addWidget(self.overview)
vbox.addWidget(splitter, 1)
vbox.addWidget(self.lb_path)
button_box = QHBoxLayout()
button_box.addWidget(self.pb_select)
button_box.addStretch(1)
button_box.addWidget(self.pb_publish)
button_box.addWidget(self.pb_zip)
vbox.addLayout(button_box)
self.setLayout(vbox)
def file_view_doubleclicked(self, index):
path = self.file_model.full_path(index.row())
webbrowser.open_new(PurePath(path).as_uri())
def file_view_clicked(self, index):
pass
def file_view_selection_changed(self, selected, deselected):
# selected, deselected: PyQt5.QtCore.QItemSelection
sindexes = selected.indexes()
if len(sindexes) > 0:
index = sindexes[0]
path = self.file_model.full_path(index.row())
self.lb_path.setText(path)
else:
self.lb_path.setText("")
#.........这里部分代码省略.........