本文整理汇总了Python中PyQt5.QtWidgets.QTableView.setSelectionMode方法的典型用法代码示例。如果您正苦于以下问题:Python QTableView.setSelectionMode方法的具体用法?Python QTableView.setSelectionMode怎么用?Python QTableView.setSelectionMode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QTableView
的用法示例。
在下文中一共展示了QTableView.setSelectionMode方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ProblemDialog
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionMode [as 别名]
class ProblemDialog(QDialog):
def __init__(self, parent, model, **kwargs):
flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
super().__init__(parent, flags, **kwargs)
self._setupUi()
self.model = model
self.model.view = self
self.table = ProblemTable(self.model.problem_table, view=self.tableView)
self.revealButton.clicked.connect(self.model.reveal_selected_dupe)
self.closeButton.clicked.connect(self.accept)
def _setupUi(self):
self.setWindowTitle(tr("Problems!"))
self.resize(413, 323)
self.verticalLayout = QVBoxLayout(self)
self.label = QLabel(self)
msg = tr(
"There were problems processing some (or all) of the files. The cause of "
"these problems are described in the table below. Those files were not "
"removed from your results."
)
self.label.setText(msg)
self.label.setWordWrap(True)
self.verticalLayout.addWidget(self.label)
self.tableView = QTableView(self)
self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.tableView.setSelectionMode(QAbstractItemView.SingleSelection)
self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
self.tableView.setShowGrid(False)
self.tableView.horizontalHeader().setStretchLastSection(True)
self.tableView.verticalHeader().setDefaultSectionSize(18)
self.tableView.verticalHeader().setHighlightSections(False)
self.verticalLayout.addWidget(self.tableView)
self.horizontalLayout = QHBoxLayout()
self.revealButton = QPushButton(self)
self.revealButton.setText(tr("Reveal Selected"))
self.horizontalLayout.addWidget(self.revealButton)
spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.closeButton = QPushButton(self)
self.closeButton.setText(tr("Close"))
self.closeButton.setDefault(True)
self.horizontalLayout.addWidget(self.closeButton)
self.verticalLayout.addLayout(self.horizontalLayout)
示例2: PreviewWidget
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionMode [as 别名]
class PreviewWidget(QWidget):
def __init__(self, student_list, column_map, parent=None):
super().__init__(parent)
self.listing = students.GroupListing(None, student_list)
self.column_map = column_map
layout = QVBoxLayout()
self.setLayout(layout)
self.table = QTableView()
self.table.setMinimumWidth(600)
self.table.setMinimumHeight(300)
layout.addWidget(self.table)
self.model = StudentsTableModel(self.listing, column_map, self)
self.table.setModel(self.model)
self.table.setSelectionMode(QTableView.NoSelection)
layout.setAlignment(self.table, Qt.AlignHCenter)
self._resize_table()
def swap_names(self):
for s in self.listing.students:
s.first_name, s.last_name = s.last_name, s.first_name
self.model.data_reset()
self._resize_table()
def to_full_name(self, column):
attr_name = students.ATTR_NAME[column]
for s in self.listing.students:
s.full_name = getattr(s, attr_name)
s.first_name = ''
s.last_name = ''
self.column_map = self.column_map.to_full_name()
self.model.data_reset(column_map=self.column_map)
self._resize_table()
def remove_duplicates(self):
self.listing.remove_students([s for s in self.listing.students
if s.is_duplicate])
self.model.data_reset()
def _resize_table(self):
for i in range(len(self.column_map) - 1):
self.table.resizeColumnToContents(i)
self.table.horizontalHeader().setStretchLastSection(True)
示例3: IgnoreListDialog
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionMode [as 别名]
class IgnoreListDialog(QDialog):
def __init__(self, parent, model, **kwargs):
flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
super().__init__(parent, flags, **kwargs)
self._setupUi()
self.model = model
self.model.view = self
self.table = IgnoreListTable(self.model.ignore_list_table, view=self.tableView)
self.removeSelectedButton.clicked.connect(self.model.remove_selected)
self.clearButton.clicked.connect(self.model.clear)
self.closeButton.clicked.connect(self.accept)
def _setupUi(self):
self.setWindowTitle(tr("Ignore List"))
self.resize(540, 330)
self.verticalLayout = QVBoxLayout(self)
self.tableView = QTableView()
self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.tableView.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
self.tableView.setShowGrid(False)
self.tableView.horizontalHeader().setStretchLastSection(True)
self.tableView.verticalHeader().setDefaultSectionSize(18)
self.tableView.verticalHeader().setHighlightSections(False)
self.tableView.verticalHeader().setVisible(False)
self.verticalLayout.addWidget(self.tableView)
self.removeSelectedButton = QPushButton(tr("Remove Selected"))
self.clearButton = QPushButton(tr("Clear"))
self.closeButton = QPushButton(tr("Close"))
self.verticalLayout.addLayout(
horizontalWrap([
self.removeSelectedButton, self.clearButton,
None, self.closeButton
])
)
#--- model --> view
def show(self):
super().show()
示例4: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionMode [as 别名]
class MainWindow(QMainWindow):
def __init__(self,system):
super(MainWindow, self).__init__()
self.system = system
fileMenu = QMenu("&Menu", self)
dbinitAction = fileMenu.addAction("사용자 정보 초기화")
quitAction = fileMenu.addAction("E&xit")
quitAction.setShortcut("Ctrl+Q")
self.menuBar().addMenu(fileMenu)
self.statusBar()
dbinitAction.triggered.connect(self.ClickAction_dbinit)
quitAction.triggered.connect(QApplication.instance().quit)
self.setupModel()
self.setupViews()
self.readDB()
self.setWindowTitle("PyStudy 학습진도창")
self.resize(870, 550)
def setupModel(self):
self.model = QStandardItemModel(3, 2, self)
self.model.setHeaderData(0, Qt.Horizontal, "목록")
self.model.setHeaderData(1, Qt.Horizontal, "읽기여부")
self.model2 = QStandardItemModel(3, 2, self)
self.model2.setHeaderData(0, Qt.Horizontal, "학습여부")
self.model2.setHeaderData(1, Qt.Horizontal, "개수")
def setupViews(self):
splitter = QSplitter()
self.table = QTableView()
self.pieChart = PieView()
splitter.addWidget(self.pieChart)
splitter.addWidget(self.table)
splitter.setStretchFactor(0, 0)
splitter.setStretchFactor(1, 0)
self.table.setModel(self.model)
self.pieChart.setModel(self.model2)
self.selectionModel = QItemSelectionModel(self.model2)
self.table.setSelectionModel(self.selectionModel)
#self.pieChart.setSelectionModel(self.selectionModel)
#table.setColumnWidth(0,100)
self.setCentralWidget(splitter)
self.table.doubleClicked.connect(self.ClickAction_table)
def readDB(self):
con = sqlite3.connect("mystudy.db")
cur = con.cursor()
cur.execute("select subject, readcheck from study;")
self.model.removeRows(0, self.model.rowCount(QModelIndex()),
QModelIndex())
self.model2.removeRows(0, self.model2.rowCount(QModelIndex()),
QModelIndex())
row = 0
for line in cur:
if line[1] ==1:
result = "○"
else:
result = "X"
self.model.insertRows(row, 1, QModelIndex())
self.model.setData(self.model.index(row, 0, QModelIndex()), line[0])
self.model.setData(self.model.index(row, 1, QModelIndex()),result)
self.model.setData(self.model.index(row, 1, QModelIndex()), QVariant(Qt.AlignCenter),Qt.TextAlignmentRole)
row += 1
cur.execute("select count() from study ;")
for line in cur:
self.studyTotal =line[0]
cur.execute("select count() from study where readcheck=1;")
for line in cur:
self.studyRead =line[0]
#print("총 개수 " ,self.studyTotal ," 학습한개수", self.studyRead )
con.close()
row=0
self.model2.insertRows(row, 1, QModelIndex())
self.model2.setData(self.model2.index(row, 0, QModelIndex()),"학습")
self.model2.setData(self.model2.index(row, 1, QModelIndex()), float(self.studyRead))
self.model2.setData(self.model2.index(row, 0, QModelIndex()), QColor("#99e600"), Qt.DecorationRole)
row=1
self.model2.insertRows(row, 1, QModelIndex())
self.model2.setData(self.model2.index(row, 0, QModelIndex()),"미학습")
self.model2.setData(self.model2.index(row, 1, QModelIndex()), float(self.studyTotal-self.studyRead))
self.model2.setData(self.model2.index(row, 0, QModelIndex()), QColor("#8080b3"), Qt.DecorationRole)
self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.table.setSelectionMode(QAbstractItemView.SingleSelection)
self.table.setDragEnabled(False)
#.........这里部分代码省略.........
示例5: ExportPanel
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionMode [as 别名]
class ExportPanel(Panel):
FIELDS = []
PERSISTENT_NAME = 'exportPanel'
def __init__(self, model, mainwindow):
Panel.__init__(self, mainwindow)
self.setAttribute(Qt.WA_DeleteOnClose)
self.mainwindow = mainwindow
self._setupUi()
self.model = model
self.accountTable = ExportAccountTable(model=self.model.account_table, view=self.tableView)
self.exportTypeButtons.buttonClicked[int].connect(self.exportTypeSelected)
self.exportFormatButtons.buttonClicked[int].connect(self.exportFormatSelected)
self.buttonBox.rejected.connect(self.reject)
self.exportButton.clicked.connect(self.exportButtonClicked)
def _setupUi(self):
self.setWindowTitle(tr("Export Options"))
self.mainLayout = QVBoxLayout(self)
self.label1 = QLabel(tr("Which accounts do you want to export?"), self)
self.mainLayout.addWidget(self.label1)
self.exportTypeButtons = QButtonGroup(self)
self.exportAllButton = QRadioButton(tr("All"), self)
self.mainLayout.addWidget(self.exportAllButton)
self.exportTypeButtons.addButton(self.exportAllButton, ExportType.All)
self.exportAllButton.setChecked(True)
self.exportSelectedButton = QRadioButton(tr("Selected"), self)
self.mainLayout.addWidget(self.exportSelectedButton)
self.exportTypeButtons.addButton(self.exportSelectedButton, ExportType.Selected)
self.tableView = QTableView(self)
self.tableView.setSelectionMode(QAbstractItemView.SingleSelection)
self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
self.tableView.verticalHeader().setVisible(False)
self.tableView.verticalHeader().setDefaultSectionSize(18)
self.mainLayout.addWidget(self.tableView)
self.label2 = QLabel(tr("Export format:"), self)
self.mainLayout.addWidget(self.label2)
self.exportFormatButtons = QButtonGroup(self)
self.exportAsQIFButton = QRadioButton("QIF", self)
self.mainLayout.addWidget(self.exportAsQIFButton)
self.exportFormatButtons.addButton(self.exportAsQIFButton, ExportFormat.QIF)
self.exportAsQIFButton.setChecked(True)
self.exportAsCSVButton = QRadioButton("CSV", self)
self.mainLayout.addWidget(self.exportAsCSVButton)
self.exportFormatButtons.addButton(self.exportAsCSVButton, ExportFormat.CSV)
self.label3 = QLabel(tr("Export scope:"))
self.mainLayout.addWidget(self.label3)
self.dateRangeOnlyCheckbox = QCheckBox(tr("Current date range only"))
self.mainLayout.addWidget(self.dateRangeOnlyCheckbox)
self.buttonBox = QDialogButtonBox(self)
self.buttonBox.setOrientation(Qt.Horizontal)
self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
self.exportButton = self.buttonBox.addButton(tr("Export"), QDialogButtonBox.ActionRole)
self.mainLayout.addWidget(self.buttonBox)
#--- Overrides
def _loadFields(self):
self.exportAllButton.setChecked(self.model.export_all)
self.exportAsQIFButton.setChecked(self.model.export_format == ExportFormat.QIF)
self.dateRangeOnlyCheckbox.setChecked(self.model.current_daterange_only)
def _saveFields(self):
self.model.current_daterange_only = self.dateRangeOnlyCheckbox.isChecked()
#--- Event Handlers
def exportButtonClicked(self):
title = tr("Export")
fileext = 'qif' if self.model.export_format == ExportFormat.QIF else 'csv'
filters = tr("{0} Files (*.{1})").format(fileext.upper(), fileext)
filename = 'export.{0}'.format(fileext)
docpath = str(QFileDialog.getSaveFileName(self.mainwindow, title, filename, filters))
if docpath:
self.model.export_path = docpath
self.accept()
def exportTypeSelected(self, typeId):
self.model.export_all = typeId == ExportType.All
def exportFormatSelected(self, typeId):
self.model.export_format = typeId
#--- model --> view
def set_table_enabled(self, enabled):
self.tableView.setEnabled(enabled)
def set_export_button_enabled(self, enabled):
self.exportButton.setEnabled(enabled)
示例6: Universe
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionMode [as 别名]
class Universe(QGroupBox):
"""
Handle Universe and display its attributes
Only one is created and display universe_selected attributes
"""
def __init__(self, parent):
super(Universe, self).__init__()
# make it available for the whole instance
self.ola = parent.ola
# intialize variable used in ola_connect method
self.old = None
self.universe_selected = None
# Create universe attributes
self.create_attributes()
# Create the view to display values
self.create_tableview()
# Add the previous UI stuffs to a layout
grid = self.create_layout()
self.grid = grid
self.setLayout(grid)
parent.vbox.addWidget(self)
self.parent = parent
def create_attributes(self):
"""
create attributes widget for the universe
"""
self.id = QSpinBox()
self.id.setReadOnly(True)
self.id.setRange(0, 65536)
self.name = QLineEdit()
self.name.textEdited.connect(self.edit_name)
self.name.setFixedWidth(200)
self.merge_mode_label = QLabel('Merge Mode')
self.merge_mode_htp_label = QLabel('HTP')
self.merge_mode_htp = QRadioButton()
self.merge_mode_ltp_label = QLabel('LTP')
self.merge_mode_ltp = QRadioButton()
self.merge_mode_ltp.toggled.connect(self.edit_merge_mode_ltp)
self.merge_mode_htp.toggled.connect(self.edit_merge_mode_htp)
def edit_name(self, name):
if self.universe_selected:
if self.ola.client.SetUniverseName(self.universe_selected.id, name):
self.parent.universes_refresh()
else:
self.parent.status("name edit failed")
if debug:
"edit universe name failed"
def edit_merge_mode_htp(self, state):
if state:
if debug:
print('switch universe to HTP merge mode')
self.edit_merge_mode(1)
def edit_merge_mode_ltp(self, state):
if state:
if debug:
print('switch universe to LTP merge mode')
self.edit_merge_mode(2)
def edit_merge_mode(self, merge_mode):
if self.universe_selected:
if self.ola.client.SetUniverseMergeMode(self.universe_selected.id, merge_mode):
self.parent.universes_refresh()
else:
self.parent.status("merge mode edit failed")
if debug:
"edit universe merge mode failed"
def create_tableview(self):
"""
create the table view for DMX values
"""
self.view = QTableView()
self.view.setSelectionMode(QAbstractItemView.NoSelection)
self.model = UniverseModel(self)
self.view.setModel(self.model)
# set up headers of the QTableView
v_headers = QHeaderView(Qt.Vertical)
self.view.setVerticalHeader(v_headers)
h_headers = QHeaderView(Qt.Horizontal)
self.view.setHorizontalHeader(h_headers)
if debug :
print('how many lines : ', v_headers.count())
print('how many columns : ', h_headers.count())
# set up rows and columns
for col in range(self.model.columnCount()):
self.view.setColumnWidth(col, 28)
for row in range(self.model.rowCount()):
self.view.setRowHeight(row, 20)
self.view.setMinimumHeight(350)
def create_layout(self):
"""
create the layout for the universe display
"""
grid = QGridLayout()
grid.addWidget(self.id, 0, 0, 1, 1)
#.........这里部分代码省略.........
示例7: ZoteroTableWidget
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionMode [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)
#.........这里部分代码省略.........
示例8: ParamModWgt
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionMode [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)
#.........这里部分代码省略.........
示例9: main
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionMode [as 别名]
def main(icon_spec):
app = QApplication(sys.argv)
main_window = QMainWindow()
def sigint_handler(*args):
main_window.close()
signal.signal(signal.SIGINT, sigint_handler)
# the timer enables triggering the sigint_handler
signal_timer = QTimer()
signal_timer.start(100)
signal_timer.timeout.connect(lambda: None)
tool_bar = QToolBar()
main_window.addToolBar(Qt.TopToolBarArea, tool_bar)
table_view = QTableView()
table_view.setSelectionBehavior(QAbstractItemView.SelectRows)
table_view.setSelectionMode(QAbstractItemView.SingleSelection)
table_view.setSortingEnabled(True)
main_window.setCentralWidget(table_view)
proxy_model = QSortFilterProxyModel()
proxy_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
proxy_model.setFilterKeyColumn(1)
table_view.setModel(proxy_model)
proxy_model.layoutChanged.connect(table_view.resizeRowsToContents)
item_model = QStandardItemModel()
proxy_model.setSourceModel(item_model)
# get all icons and their available sizes
icons = []
all_sizes = set([])
for context, icon_names in icon_spec:
for icon_name in icon_names:
icon = QIcon.fromTheme(icon_name)
sizes = []
for size in icon.availableSizes():
size = (size.width(), size.height())
sizes.append(size)
all_sizes.add(size)
sizes.sort()
icons.append({
'context': context,
'icon_name': icon_name,
'icon': icon,
'sizes': sizes,
})
all_sizes = list(all_sizes)
all_sizes.sort()
# input field for filter
def filter_changed(value):
proxy_model.setFilterRegExp(value)
table_view.resizeRowsToContents()
filter_line_edit = QLineEdit()
filter_line_edit.setMaximumWidth(200)
filter_line_edit.setPlaceholderText('Filter name')
filter_line_edit.setToolTip('Filter name optionally using regular expressions (' + QKeySequence(QKeySequence.Find).toString() + ')')
filter_line_edit.textChanged.connect(filter_changed)
tool_bar.addWidget(filter_line_edit)
# actions to toggle visibility of available sizes/columns
def action_toggled(index):
column = 2 + index
table_view.setColumnHidden(column, not table_view.isColumnHidden(column))
table_view.resizeColumnsToContents()
table_view.resizeRowsToContents()
signal_mapper = QSignalMapper()
for i, size in enumerate(all_sizes):
action = QAction('%dx%d' % size, tool_bar)
action.setCheckable(True)
action.setChecked(True)
tool_bar.addAction(action)
action.toggled.connect(signal_mapper.map)
signal_mapper.setMapping(action, i)
# set tool tip and handle key sequence
tool_tip = 'Toggle visibility of column'
if i < 10:
digit = ('%d' % (i + 1))[-1]
tool_tip += ' (%s)' % QKeySequence('Ctrl+%s' % digit).toString()
action.setToolTip(tool_tip)
signal_mapper.mapped.connect(action_toggled)
# label columns
header_labels = ['context', 'name']
for width, height in all_sizes:
header_labels.append('%dx%d' % (width, height))
item_model.setColumnCount(len(header_labels))
item_model.setHorizontalHeaderLabels(header_labels)
# fill rows
item_model.setRowCount(len(icons))
for row, icon_data in enumerate(icons):
# context
item = QStandardItem(icon_data['context'])
item.setFlags(item.flags() ^ Qt.ItemIsEditable)
item_model.setItem(row, 0, item)
# icon name
#.........这里部分代码省略.........
示例10: columnCount
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionMode [as 别名]
def columnCount(self, parent):
return 3
def data(self, index, role):
if role == Qt.DisplayRole:
return "({},{})".format(index.row(), index.column())
return QVariant()
if __name__ == '__main__':
app = QApplication(sys.argv)
table_view = QTableView()
my_model = MyModel(None)
table_view.setModel(my_model)
table_view.setSelectionMode(QAbstractItemView.SingleSelection) # <- Set selection mode. See http://doc.qt.io/qt-5/qabstractitemview.html#selectionMode-prop
#table_view.setSelectionMode(QAbstractItemView.ContiguousSelection) # <- Set selection mode. See http://doc.qt.io/qt-5/qabstractitemview.html#selectionMode-prop
#table_view.setSelectionMode(QAbstractItemView.ExtendedSelection) # <- Set selection mode. See http://doc.qt.io/qt-5/qabstractitemview.html#selectionMode-prop
#table_view.setSelectionMode(QAbstractItemView.MultiSelection) # <- Set selection mode. See http://doc.qt.io/qt-5/qabstractitemview.html#selectionMode-prop
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)
示例11: ExportFrame
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionMode [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("")
#.........这里部分代码省略.........
示例12: FilterableTable
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionMode [as 别名]
class FilterableTable(SQLTable):
"""a filterable Table Widget that displays content of an SQLite table;
for individual widgets, subclass
and overwrite the create_model method;
add_color_proxy should be an (INT allele_status-column, INT lab_status-column) tuple
"""
def __init__(self, log, mydb = ": memory :", add_color_proxy = False, header_dic = None):
super().__init__(log, mydb)
self.add_color_proxy = add_color_proxy
self.header_dic = header_dic
self.create_model()
self.fill_UI()
self.create_filter_model()
self.update_filterbox()
def fill_UI(self):
"""sets up the layout
"""
self.log.debug("\t- Setting up the table...")
self.table = QTableView()
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
self.header = self.table.horizontalHeader() # table header
self.header.setSectionResizeMode(QHeaderView.ResizeToContents)
self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.table.setAlternatingRowColors(True)
# self.header.sectionClicked.connect(self.on_header_sectionClicked)
mode = QAbstractItemView.SingleSelection
self.table.setSelectionMode(mode)
self.grid.addWidget(self.table, 2, 0, 10, 10)
self.filter_lbl = QLabel("Filter:", self)
self.grid.addWidget(self.filter_lbl, 1, 2)
self.filter_entry = QLineEdit(self)
self.grid.addWidget(self.filter_entry, 1, 3)
self.filter_entry.textChanged.connect(self.on_filter_entry_textChanged)
self.filter_text = ""
self.filter_cb = QComboBox(self)
self.grid.addWidget(self.filter_cb, 1, 4)
self.filter_cb.currentIndexChanged.connect(self.on_filter_cb_IndexChanged)
self.filter_btn = QPushButton("Filter!", self)
self.grid.addWidget(self.filter_btn, 1, 5)
self.filter_btn.clicked.connect(self.on_filter_btn_clicked)
self.unfilter_btn = QPushButton("Remove Filter", self)
self.grid.addWidget(self.unfilter_btn, 1, 6)
self.unfilter_btn.clicked.connect(self.on_actionAll_triggered)
self.log.debug("\t=> Done!")
def update_filterbox(self):
"""fills the filter-combobox with the header values
after the model has been created and set
"""
column_num = self.model.columnCount()
if self.header_dic:
columns = [self.header_dic[i] for i in self.header_dic]
else:
columns = [self.proxy.headerData(i, Qt.Horizontal) for i in range(column_num)]
self.filter_cb.addItems(columns)
def create_filter_model(self):
"""creates the filter-proxy-model on top of self.model
"""
self.log.debug("Creating filter model...")
self.proxy = QSortFilterProxyModel(self)
if self.add_color_proxy:
(allele_status_column, lab_status_column) = self.add_color_proxy
self.log.debug("adding color filter to columns {} and {}".format(allele_status_column, lab_status_column))
self.color_proxy = ColorProxyModel(self, allele_status_column, lab_status_column)
self.color_proxy.setSourceModel(self.model)
self.proxy.setSourceModel(self.color_proxy)
else:
self.proxy.setSourceModel(self.model)
self.table.setSortingEnabled(True)
self.table.setModel(self.proxy)
def on_filter_cb_IndexChanged(self, index):
"""restricts RegEx filter to selected column
"""
self.log.debug("Combobox: colum {} selected".format(index))
self.proxy.setFilterKeyColumn(index)
def on_filter_entry_textChanged(self, text):
"""stores content of filter_entry as self.text
"""
self.log.debug("filter text: '{}'".format(text))
self.filter_text = text
def on_filter_btn_clicked(self):
"""activates RegEx filter to current content of filter_entry and filter_cb
"""
column = self.filter_cb.currentIndex()
self.log.debug("Filtering column {} for '{}'".format(column, self.filter_text))
self.proxy.setFilterKeyColumn(column)
search = QRegExp(self.filter_text, Qt.CaseInsensitive, QRegExp.RegExp)
#.........这里部分代码省略.........