本文整理汇总了Python中PyQt5.QtWidgets.QTableView.setSortingEnabled方法的典型用法代码示例。如果您正苦于以下问题:Python QTableView.setSortingEnabled方法的具体用法?Python QTableView.setSortingEnabled怎么用?Python QTableView.setSortingEnabled使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QTableView
的用法示例。
在下文中一共展示了QTableView.setSortingEnabled方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: draw_table
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSortingEnabled [as 别名]
def draw_table():
tv = QTableView()
tv.setMinimumSize(400, 400)
tv.setShowGrid(False)
vh = tv.verticalHeader()
vh.setVisible(False)
hh = tv.horizontalHeader()
hh.setStretchLastSection(True)
tv.setSortingEnabled(True)
return tv
示例2: SetupUI
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSortingEnabled [as 别名]
def SetupUI(self, w):
info("SetupUI")
# Search bar
lblName = QLabel('Search')
lblResults = QLabel('Results')
# Plugin table
ledtName = QLineEdit()
tblResults = QTableView()
tblResultsModel = PluginTableModel(self.available_plugins, Plugin.SQLITE_COLUMNS, w)
tblResults.setModel( tblResultsModel )
tblResults.horizontalHeader().setStretchLastSection(True)
tblResults.verticalHeader().setVisible(False)
tblResults.resizeColumnsToContents()
tblResults.setSortingEnabled(True)
tblResults.setFont( QFont("Courier New", 8) )
tblResults.setShowGrid(False)
## event handlers
ledtName.textChanged.connect(self.OnSearchFieldChange)
# Button row
btnUpdate = QPushButton("Refresh Plugins List")
btnInstall = QPushButton("Install")
## event handlers
btnUpdate.clicked.connect(self.RefreshPluginsList)
btnInstall.clicked.connect(self.InstallSelected)
grid = QGridLayout()
grid.addWidget(lblName, 1, 0)
grid.addWidget(ledtName, 1, 1)
grid.addWidget(lblResults, 2, 0)
grid.addWidget(tblResults, 2, 1, 5, 1)
vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addWidget(btnUpdate)
vbox.addWidget(btnInstall)
wButtons = QWidget()
wButtons.setLayout(vbox)
grid.addWidget(wButtons, 5, 1, 4, 1)
w.setLayout(grid)
return
示例3: createLibraryPlaylisView
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSortingEnabled [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])
示例4: ZoteroTableWidget
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSortingEnabled [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)
#.........这里部分代码省略.........
示例5: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSortingEnabled [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)
#.........这里部分代码省略.........
示例6: data
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSortingEnabled [as 别名]
return self.data.shape[1]
def data(self, index, role):
if role == Qt.DisplayRole:
return "{}".format(self.data[index.row(), index.column()])
return QVariant()
if __name__ == '__main__':
app = QApplication(sys.argv)
table_view = QTableView()
my_model = MyModel(None)
proxy_model = QSortFilterProxyModel() # <--
proxy_model.setSourceModel(my_model) # <--
table_view.setModel(proxy_model) # <--
#table_view.setModel(my_model)
table_view.setSortingEnabled(True) # <--
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: main
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSortingEnabled [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
#.........这里部分代码省略.........
示例8: ExportFrame
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSortingEnabled [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("")
#.........这里部分代码省略.........
示例9: FnotePanel
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSortingEnabled [as 别名]
#.........这里部分代码省略.........
'A Footnote zone is defined by "/F" and "F/" lines.' )
utilities.warning_msg(emsg,expl,self)
return
# create a working cursor and start an undo macro on it.
worktc = self.edit_view.get_cursor()
worktc.beginEditBlock()
# Do the actual work inside a try-finally block so as to be sure
# that the Edit Block is ultimately closed.
try :
self.data_model.move_notes(worktc)
except Exception as whatever:
fnotview_logger.error(
'Unexpected error moving footnotes: {}'.format(whatever.args)
)
worktc.endEditBlock()
self.do_refresh()
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Set-up functions for initializing the UI elements.
# convenience functions to shorten the code of setting up 6 similar menus.
# make a combobox loaded with the stream names and set to a particular one.
def _make_cb(self, default, text) :
cb = QComboBox()
cb.addItems(stream_names)
cb.setCurrentIndex(default)
tt = _TR( 'Footnote panel popup menus',
'Choose the format to use when renumbering Note Keys such as:',
'will be followed by e.g. "[A]" or "[5]"' )
cb.setToolTip(tt+text)
return cb
# combine a combobox with a label in an hbox
def _make_pair(self, cb, caption):
hb = QHBoxLayout()
hb.addWidget( QLabel(caption) )
hb.addWidget(cb)
return hb
def _uic(self):
main_layout = QVBoxLayout()
self.setLayout(main_layout)
# make a horizontal layout of [Refresh Renumber Move]
top_box = QHBoxLayout()
# make the Refresh button with translated text
self.refresh_button = QPushButton(
_TR('Footnote panel Refresh button', 'Refresh') )
self.refresh_button.setToolTip(
_TR('Footnote panel Refresh button',
'Scan the book to find all footnotes and match them to their anchors' ) )
top_box.addWidget(self.refresh_button,0)
top_box.addStretch(1) # push next two buttons to the right
# Make the Renumber button
self.renumber_button = QPushButton(
_TR('Footnote panel Renumber button', 'Renumber') )
self.renumber_button.setToolTip(
_TR('Footnote panel Renumber button',
'Renumber all footnotes using the styles chosen in the menus below') )
top_box.addWidget(self.renumber_button,0)
# Make the Move button
self.move_button = QPushButton(
_TR('Footnote panel Move-to-zones button','Move to Zones') )
self.move_button.setToolTip(
_TR('Footnote panel Move button',
'Move all footnotes into zones marked /F ... F/' ) )
top_box.addWidget(self.move_button,0)
# Put that row of buttons at the top of the panel
main_layout.addLayout(top_box,0)
# Create the table, a very basic one, no sorting etc.
self.model = FnoteTableModel(self.data_model, self)
self.view = QTableView()
self.view.setModel(self.model)
self.view.setCornerButtonEnabled(False)
self.view.setWordWrap(False)
self.view.setAlternatingRowColors(False)
self.view.setSortingEnabled(False)
main_layout.addWidget(self.view,1) # Table gets all the stretch
# Create the six combo boxes. Initialize both IVX and ABC to
# the ABC stream and ivx and abc to the abc.
self.pick_IVX = self._make_cb(fnotdata.KeyClass_ABC, '[II]')
self.pick_ABC = self._make_cb(fnotdata.KeyClass_ABC, '[B]' )
self.pick_ivx = self._make_cb(fnotdata.KeyClass_abc, '[vi]')
self.pick_abc = self._make_cb(fnotdata.KeyClass_abc, '[b]' )
self.pick_123 = self._make_cb(fnotdata.KeyClass_123, '[2]' )
self.pick_sym = self._make_cb(fnotdata.KeyClass_sym, '[§]' )
# Create a 2x3 grid layout and put a label:combobox in each cell
grid = QGridLayout()
grid.addLayout( self._make_pair( self.pick_ABC, key_class_names[1] ), 0, 0)
grid.addLayout( self._make_pair( self.pick_IVX, key_class_names[0] ), 1, 0)
grid.addLayout( self._make_pair( self.pick_abc, key_class_names[3] ), 0, 1)
grid.addLayout( self._make_pair( self.pick_ivx, key_class_names[2] ), 1, 1)
grid.addLayout( self._make_pair( self.pick_123, key_class_names[4] ), 0, 2)
grid.addLayout( self._make_pair( self.pick_sym, key_class_names[5] ), 1, 2)
# Put the grid in an hbox with stretch on each side to center it
gridhb = QHBoxLayout()
gridhb.addStretch(1)
gridhb.addLayout(grid,0)
gridhb.addStretch(1)
# Add that row to the main layout
main_layout.addLayout(gridhb)
# End of _uic
示例10: FilterableTable
# 需要导入模块: from PyQt5.QtWidgets import QTableView [as 别名]
# 或者: from PyQt5.QtWidgets.QTableView import setSortingEnabled [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)
#.........这里部分代码省略.........