Search/Find functionality in QTableView

2024/9/30 9:28:19

I have a QWidget and inside that, there is a QTableView. I need to have a find functionality on the first column of the table, so when I click on Ctrl+F, a find dialog will pop-up.

class Widget(QWidget):def __init__(self,md,parent=None):QWidget.__init__(self,parent)layout=QVBoxLayout(self)# initially construct the visible tabletv = QTableView()# uncomment this if the last column shall cover the resttv.horizontalHeader().setStretchLastSection(True)tv.show()# set black grid linesself.setStyleSheet("gridline-color: rgb(39, 42, 49)")# construct the Qt model belonging to the visible tablemodel = NvmQtModel(md)tv.setModel(model)tv.resizeRowsToContents()tv.resizeColumnsToContents()# set the shortcut ctrl+F for find in menushortcut = QShortcut(QKeySequence('Ctrl+f'), self)shortcut.activated.connect(self.handleFind)# delegate for decimaldelegate = NvmDelegate()tv.setItemDelegate(delegate)self.setGeometry(200,200,600,600) # adjust this laterlayout.addWidget(tv)# set window titleself.setWindowTitle("TITLE")# shows and handles the find dialogdef handleFind(self):findDialog = QDialog()grid = QGridLayout()findDialog.setLayout(grid)findLabel = QLabel("Find what", findDialog)grid.addWidget(findLabel,1,0)findField = QLineEdit(findDialog)grid.addWidget(findField,1,1)findButton = QPushButton("Find", findDialog)findButton.clicked.connect(self.find)grid.addWidget(findButton,2,1)findDialog.exec_()# find function: search in the first column of the table   def find(self):#to do# prevent closing the window  without confirmationdef closeEvent(self, event):reply=QMessageBox.question(self,'Message',"Are you sure to quit?",QMessageBox.Yes|QMessageBox.No,QMessageBox.No)if reply==QMessageBox.Yes:event.accept()else:event.ignore()# create the application and the new tree view container
app=QApplication(sys.argv)
wid=Widget(md)
wid.show()
wid.raise_()

I have problem in the findButton action where it should search in the first column of the table. I would appreciate if you guide me in this issue.

Answer

Firstly, you will need to change the way the findButton is connected, so that it sends the text to be searched for:

findButton.clicked.connect(lambda: self.find(findField.text()))

Then you can search in your table by using the match method of the tableview's model:

def find(self, text, column=0):model = self.table.model()start = model.index(0, column)matches = model.match(start, QtCore.Qt.DisplayRole,text, 1, QtCore.Qt.MatchContains)if matches:index = matches[0]# index.row(), index.column()self.table.selectionModel().select(index, QtGui.QItemSelectionModel.Select)

UPDATE:

The method above will find the first cell that contains the given text, and then select it. If you wanted to find the next cell that matches, start would need to be set to the appropriate index of the current selection (if there is one). This could be obtained with:

    indexes = self.table.selectionModel().selectedIndexes()
https://en.xdnf.cn/q/71100.html

Related Q&A

How does searching with pip work?

Yes, Im dead serious with this question. How does searching with pip work?The documentation of the keyword search refers to a "pip search reference" at https://pip.pypa.io/en/stable/user_gui…

keras LSTM feeding input with the right shape

I am getting some data from a pandas dataframe with the following shapedf.head() >>> Value USD Drop 7 Up 7 Mean Change 7 Change Predict 0.06480 2.0 4.0 -0.000429 …

Problems with a binary one-hot (one-of-K) coding in python

Binary one-hot (also known as one-of-K) coding lies in making one binary column for each distinct value for a categorical variable. For example, if one has a color column (categorical variable) that ta…

How to hide the title bar in pygame?

I was wondering does anyone know how to hide the pygame task bar?I really need this for my pygame program!Thanks!

Deleting existing class variable yield AttributeError

I am manipulating the creation of classes via Pythons metaclasses. However, although a class has a attribute thanks to its parent, I can not delete it.class Meta(type):def __init__(cls, name, bases, dc…

Setting global font size in kivy

What is the preferred way, whether through python or the kivy language, to set the global font size (i.e. for Buttons and Labels) in kivy? What is a good way to dynamically change the global font size…

What is the difference between load name and load global in python bytecode?

load name takes its argument and pushes onto the stack the value of the name stored by store name at the position indicated by the argument . load global does something similar, but there appears to …

porting Python 2 program to Python 3, random line generator

I have a random line generator program written in Python2, but I need to port it to Python3. You give the program the option -n [number] and a file argument to tell it to randomly output [number] numbe…

Symbol not found, Expected in: flat namespace

I have a huge gl.pxd file with all the definitions of gl.h, glu.h and glut.h. For example it has these lines:cdef extern from <OpenGL/gl.h>:ctypedef unsigned int GLenumcdef void glBegin( GLenum m…

Why does Django not generate CSRF or Session Cookies behind a Varnish Proxy?

Running Django 1.2.5 on a Linux server with Apache2 and for some reason Django seems like it cannot store CSRF or Session cookies. Therefore when I try to login to the Django admin it gives me a CSRF v…