本文整理汇总了Python中PyQt5.QtWidgets.QTableView.model方法的典型用法代码示例。如果您正苦于以下问题:Python QTableView.model方法的具体用法?Python QTableView.model怎么用?Python QTableView.model使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QTableView
的用法示例。
在下文中一共展示了QTableView.model方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MyWin
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import model [as 别名]
class MyWin(QWidget):
def __init__(self, mydb):
super(MyWin, self).__init__()
main_lt = QVBoxLayout()
self.view = QTableView()
main_lt.addWidget(self.view)
self.view.setWindowTitle("Table Model (View 1)")
self.view.setSelectionBehavior(QAbstractItemView.SelectRows)
self.mydb = mydb
button = QPushButton("Join")
button.clicked.connect(self.merge)
main_lt.addWidget(button)
button = QPushButton("Exit")
button.clicked.connect(lambda: exit())
main_lt.addWidget(button)
self.setLayout(main_lt)
self.setWindowTitle('QT1')
def set_model(self):
self.view.setModel(self.mydb.get_model())
def merge(self):
ind_list = self.view.selectedIndexes()
out = list(self.view.model().data(i) for i in ind_list)
out = [out[i] for i in range(len(out)) if i % 2 == 0]
if len(out) < 2:
return
self.mydb.merge(out)
mb = QMessageBox()
mb.setText('Merged %s' % str(out))
mb.exec_()
self.set_model()
示例2: RelationDialog
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import model [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: ZoteroTableWidget
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import model [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)
#.........这里部分代码省略.........
示例4: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import model [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)
#.........这里部分代码省略.........
示例5: ListView
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import model [as 别名]
class ListView(QStackedWidget):
PAGE_EMPTY = 0
PAGE_LISTVIEW = 1
def __init__(self, parent = None):
super(ListView, self).__init__(parent=parent)
self.emptyMessage = QLabel("no elements defined yet")
self.emptyMessage.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter )
self.emptyMessage.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.addWidget(self.emptyMessage)
self._table = QTableView()
self.addWidget(self._table)
self._table.clicked.connect(self.tableViewCellClicked)
self._table.doubleClicked.connect(self.tableViewCellDoubleClicked)
self._table.verticalHeader().sectionMoved.connect(self.rowMovedTest)
self._table.setShowGrid(False)
def resetEmptyMessage(self,pystring):
self.emptyMessage.setText(pystring)
def tableViewCellClicked(self, modelIndex):
'''
Reimplemt this function to get interaction when double click
:param modelIndex:
'''
# if (modelIndex.column() == self.model.ColumnID.Delete and
# not self._table.model().flags(modelIndex) == Qt.NoItemFlags):
# self._table.model().removeRow(modelIndex.row())
#
def tableViewCellDoubleClicked(self, modelIndex):
'''
Reimplement this function to get interaction when single click
:param modelIndex:
'''
# if modelIndex.column() == self.model.ColumnID.Color:
# self._colorDialog.setBrushColor(self._table.model()[modelIndex.row()].brushColor())
# self._colorDialog.setPmapColor (self._table.model()[modelIndex.row()].pmapColor())
# self._colorDialog.exec_()
# #print "brush color = {}".format(self._colorDialog.brushColor().name())
# #print "pmap color = {}".format(self._colorDialog.pmapColor().name())
# self._table.model().setData(modelIndex, (self._colorDialog.brushColor(),
# self._colorDialog.pmapColor ()))
def rowMovedTest(self, logicalIndex, oldVisualIndex, newVisualIndex):
logger.debug( "{} {} {}".format(logicalIndex, oldVisualIndex, newVisualIndex) )
def _setListViewLook(self):
table = self._table
#table.setDragEnabled(True)
table.setAcceptDrops(True)
table.setFocusPolicy(Qt.NoFocus)
table.setShowGrid(False)
table.horizontalHeader().hide()
table.verticalHeader().hide()
#table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
table.setSelectionMode(QAbstractItemView.SingleSelection)
table.setSelectionBehavior(QAbstractItemView.SelectRows)
def selectRow(self, *args, **kwargs):
self._table.selectRow(*args, **kwargs)
def _onRowsChanged(self, parent, start, end):
model = self._table.model()
if model and model.rowCount() > 0:
self.setCurrentIndex(self.PAGE_LISTVIEW)
else:
self.setCurrentIndex(self.PAGE_EMPTY)
if self.parent()!=None: self.parent().updateGeometry()
def setModel(self, model):
QTableView.setModel(self._table, model)
self._table.setSelectionModel(model._selectionModel)
if model.rowCount() > 0:
self.setCurrentIndex(self.PAGE_LISTVIEW)
else:
self.setCurrentIndex(self.PAGE_EMPTY)
model.rowsInserted.connect(self._onRowsChanged)
model.rowsRemoved.connect(self._onRowsChanged)
self.model=model
self._setListViewLook()
@property
def allowDelete(self):
return not self._table.isColumnHidden(self.model.ColumnID.Delete)
@allowDelete.setter
def allowDelete(self, allow):
self._table.setColumnHidden(self.model.ColumnID.Delete, not allow)
#.........这里部分代码省略.........
示例6: ParamModWgt
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import model [as 别名]
#.........这里部分代码省略.........
if len(self.paramListTblWdg.selectionModel().selectedRows()) == 0:
selectedRow = -1
if selectedRow >= 0:
self.main_window.currentAnnotation.parameters[selectedRow] = param
else:
self.main_window.currentAnnotation.parameters.append(param)
self.additionMode = False
nbParams = len(self.main_window.currentAnnotation.parameters)
self.main_window.saveAnnotation()
if selectedRow < 0 :
selectedRow = nbParams-1
self.paramListTblWdg.selectRow(selectedRow)
self.loadRow(selectedRow)
def deleteParameter(self):
selectedRow = self.paramListTblWdg.selectionModel().currentIndex().row()
del self.main_window.currentAnnotation.parameters[selectedRow]
self.main_window.saveAnnotation()
self.refreshModelingParameters()
def refreshModelingParameters(self):
selectedRow = self.paramListTblWdg.selectionModel().currentIndex().row()
self.loadModelingParameter(selectedRow)
def loadModelingParameter(self, row = None):
"""
Call when a new annotation has been selected so that all the modeling parameters
associated with this annotation are loaded in the parameter list.
"""
self.requiredTagsListModel.clear()
self.requiredTagsListModel.refresh()
if self.main_window.currentAnnotation is None:
self.paramListModel.parameterList = []
else:
self.paramListModel.parameterList = self.main_window.currentAnnotation.parameters
aRowIsSelected = not row is None
if aRowIsSelected:
if row < 0:
noRowToLoad = self.paramListTblWdg.model().rowCount()-row
else:
noRowToLoad = row
else:
## No rows are selected
noRowToLoad = -1
self.loadRow(noRowToLoad)
self.newParamBtn.setEnabled(True)
self.deleteParamBtn.setEnabled(aRowIsSelected)
self.paramSaveAnnotBtn.setEnabled(aRowIsSelected)
self.paramModStack.currentWidget().loadModelingParameter(row)
self.relationWgt.loadModelingParameter(row)
self.newParamsGB.setEnabled(aRowIsSelected)
self.paramListModel.refresh()