本文整理汇总了Python中PyQt5.QtWidgets.QTableView.setSelectionBehavior方法的典型用法代码示例。如果您正苦于以下问题:Python QTableView.setSelectionBehavior方法的具体用法?Python QTableView.setSelectionBehavior怎么用?Python QTableView.setSelectionBehavior使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QTableView
的用法示例。
在下文中一共展示了QTableView.setSelectionBehavior方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: GroupWidget
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [as 别名]
class GroupWidget(QWidget):
_COLUMN_MAP = students.StudentColumnMap(
columns=[
students.StudentColumn.SEQUENCE_NUM,
students.StudentColumn.ID,
students.StudentColumn.NAME,
])
def __init__(self, listing, student_tabs):
super().__init__(student_tabs.tabs)
self.listing = listing
layout = QVBoxLayout()
self.setLayout(layout)
self.table = QTableView()
self.table.setMinimumWidth(500)
self.table.setMinimumHeight(300)
layout.addWidget(self.table)
self.model = StudentsTableModel(listing, GroupWidget._COLUMN_MAP, self)
self.table.setModel(self.model)
self.table.setSelectionBehavior(QTableView.SelectRows)
layout.setAlignment(self.table, Qt.AlignHCenter)
self._resize_table()
def add_students(self, student_list):
self.listing.add_students(student_list)
self.listing_updated()
def listing_updated(self):
self.model.data_reset()
self._resize_table()
def _resize_table(self):
self.table.resizeColumnToContents(0)
self.table.horizontalHeader().setStretchLastSection(True)
示例2: MyWin
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [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()
示例3: ProblemDialog
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [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)
示例4: createLibraryPlaylisView
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [as 别名]
def createLibraryPlaylisView(self, uuid):
playlistModel = PlaylistModel(uuid)
playlistView = QTableView(self)
playlistView.setModel(playlistModel)
playlistView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
playlistView.setSortingEnabled(True)
playlistView.setSelectionBehavior(QAbstractItemView.SelectRows)
playlistView.setShowGrid(False)
playlistView.horizontalHeader().setSectionResizeMode(
QHeaderView.Stretch)
playlistView.doubleClicked.connect(self._doubleCLickedWidget)
playlistView.customContextMenuRequested.connect(
self.customMenuRequested)
self.playlistMappings[uuid] = playlistView
self.insertWidget(0, playlistView)
self.setCurrentWidget(self.playlistMappings[uuid])
示例5: IgnoreListDialog
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [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()
示例6: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [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)
#.........这里部分代码省略.........
示例7: ExportPanel
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [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)
示例8: RelationDialog
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [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)
示例9: print
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [as 别名]
# The following line are necessary e.g. to dynamically update the QSortFilterProxyModel
self.dataChanged.emit(index, index, [Qt.EditRole])
except Exception as e:
print(e)
return False
return True
def flags(self, index):
return Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled
if __name__ == '__main__':
app = QApplication(sys.argv)
data = MyData()
table_view = QTableView()
my_model = MyModel(data)
table_view.setModel(my_model)
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 )
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)
开发者ID:jeremiedecock,项目名称:snippets,代码行数:33,代码来源:widget_QTableView_selection_behavior_select_full_row.py
示例10: ZoteroTableWidget
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [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)
#.........这里部分代码省略.........
示例11: CSVOptionsWindow
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [as 别名]
class CSVOptionsWindow(QWidget):
def __init__(self, mainwindow):
QWidget.__init__(self, mainwindow, Qt.Window)
self._setupUi()
self.doc = mainwindow.doc
self.model = mainwindow.model.csv_options
self.tableModel = CSVOptionsTableModel(self.model, self.tableView)
self.model.view = self
self.encodingComboBox.addItems(SUPPORTED_ENCODINGS)
self.cancelButton.clicked.connect(self.hide)
self.continueButton.clicked.connect(self.model.continue_import)
self.targetComboBox.currentIndexChanged.connect(self.targetIndexChanged)
self.layoutComboBox.currentIndexChanged.connect(self.layoutIndexChanged)
self.rescanButton.clicked.connect(self.rescanClicked)
def _setupUi(self):
self.setWindowTitle(tr("CSV Options"))
self.resize(526, 369)
self.verticalLayout = QVBoxLayout(self)
msg = tr(
"Specify which CSV columns correspond to which transaction fields. You must also "
"uncheck the \"Import\" column for lines that don\'t represent a transaction "
"(header, footer, comments)."
)
self.label = QLabel(msg)
self.label.setWordWrap(True)
self.verticalLayout.addWidget(self.label)
self.gridLayout = QGridLayout()
self.label_2 = QLabel(tr("Layout:"))
self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1)
self.layoutComboBox = QComboBox(self)
self.layoutComboBox.setMinimumSize(QtCore.QSize(160, 0))
self.gridLayout.addWidget(self.layoutComboBox, 0, 1, 1, 1)
self.label_4 = QLabel(tr("Delimiter:"))
self.gridLayout.addWidget(self.label_4, 0, 3, 1, 1)
self.fieldSeparatorEdit = QLineEdit(self)
self.fieldSeparatorEdit.setMaximumSize(QtCore.QSize(30, 16777215))
self.gridLayout.addWidget(self.fieldSeparatorEdit, 0, 4, 1, 1)
self.targetComboBox = QComboBox(self)
self.gridLayout.addWidget(self.targetComboBox, 1, 1, 1, 1)
self.label_3 = QLabel(tr("Target:"))
self.gridLayout.addWidget(self.label_3, 1, 0, 1, 1)
self.encodingComboBox = QComboBox(self)
self.gridLayout.addWidget(self.encodingComboBox, 1, 4, 1, 1)
spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.gridLayout.addItem(spacerItem, 2, 2, 1, 1)
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setSpacing(0)
spacerItem1 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem1)
self.rescanButton = QPushButton(tr("Rescan"))
sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.rescanButton.sizePolicy().hasHeightForWidth())
self.rescanButton.setSizePolicy(sizePolicy)
self.horizontalLayout_2.addWidget(self.rescanButton)
self.gridLayout.addLayout(self.horizontalLayout_2, 2, 3, 1, 2)
self.label_5 = QLabel(tr("Encoding:"))
self.gridLayout.addWidget(self.label_5, 1, 3, 1, 1)
self.verticalLayout.addLayout(self.gridLayout)
self.tableView = QTableView(self)
self.tableView.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)
self.tableView.setShowGrid(False)
self.tableView.horizontalHeader().setHighlightSections(False)
self.tableView.verticalHeader().setVisible(False)
self.tableView.verticalHeader().setDefaultSectionSize(18)
self.verticalLayout.addWidget(self.tableView)
self.horizontalLayout = QHBoxLayout()
spacerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem2)
self.cancelButton = QPushButton(tr("Cancel"))
self.cancelButton.setShortcut("Esc")
self.horizontalLayout.addWidget(self.cancelButton)
self.continueButton = QPushButton(tr("Continue Import"))
self.continueButton.setDefault(True)
self.horizontalLayout.addWidget(self.continueButton)
self.verticalLayout.addLayout(self.horizontalLayout)
# --- Private
def _newLayout(self):
title = tr("New Layout")
msg = tr("Choose a name for your new layout:")
name, ok = QInputDialog.getText(self, title, msg)
if ok and name:
self.model.new_layout(name)
def _renameLayout(self):
title = tr("Rename Layout")
msg = tr("Choose a name for your layout:")
name, ok = QInputDialog.getText(self, title, msg)
if ok and name:
self.model.rename_selected_layout(name)
# --- Event Handling
def layoutIndexChanged(self, index):
# This one is a little complicated. We want to only be able to select the layouts. If
# anything else is clicked, we revert back to the old index. If the item has user data,
#.........这里部分代码省略.........
示例12: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [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)
#.........这里部分代码省略.........
示例13: ParamModWgt
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [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)
#.........这里部分代码省略.........
示例14: main
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [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
#.........这里部分代码省略.........
示例15: ExportFrame
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSelectionBehavior [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("")
#.........这里部分代码省略.........