How QRegularExpression can be passed to Qt::MatchRegularExpression

2024/7/8 4:07:55

I am trying this sample code that I found which is really really good. I am also trying to figure out the same thing to find an item and scroll to it, but this time I wanted to match the the string which has the EXACT WORD "cat".

Example matches:

  • cat

  • tom cat

  • dog and cat

  • super cat

To make it very simple I am just trying to match an exact word in a string. Take this sample code as an example:

import re
s= "1  tom cat"
s2 = "2 thundercat"if re.search(r'\bcat\b',s2):print("There is an EXACT word cat in that string")
else:print("There is NO EXACT word cat in that string")

Input: s
Output: There is an EXACT word cat in that stringInput: s2
Output: There is NO EXACT word cat in that string

But this time I am using the regular expression r'\bcat\b' to check if the string has the exact word cat AND SCROLL to it

I configured it & tried this code. I just did some minor changes like the QtCore.Qt.MatchRegExp into QtCore.Qt.MatchContains which scrolls me to the word that contains "cat".

from PyQt5 import QtCore,QtWidgetsapp=QtWidgets.QApplication([])def scroll():#QtCore.QRegularExpression(r'\b'+'cat'+'\b')item = listWidget.findItems('cat', QtCore.Qt.MatchContains)[0]item.setSelected(True)window = QtWidgets.QDialog()
window.setLayout(QtWidgets.QVBoxLayout())
listWidget = QtWidgets.QListWidget()
window.layout().addWidget(listWidget)cats = ["thundercat","cat","tom cat","dogcat","dog and cat","super cat","lazycat"]for i,cat in enumerate(cats):QtWidgets.QListWidgetItem(f"{i}  {cat}", listWidget)btn = QtWidgets.QPushButton('Scroll')
btn.clicked.connect(scroll)
window.layout().addWidget(btn)
window.show()
app.exec_()

sample gui

Now I have read about this Qt::MatchRegularExpression & I was hoping to use this to achieve my goal which is scroll to the string with the EXACT WORD which contains "cat". Based on the documentation it says here.

Qt::MatchRegularExpression

Performs string-based matching using a regular expression as the search term. Uses QRegularExpression. When using this flag, a QRegularExpression object can be passed as parameter and will directly be used to perform the search. The case sensitivity flag will be ignored as the QRegularExpression object is expected to be fully configured. This enum value was added in Qt 5.15.

I can't seem to figure this out QRegularExpression object can be passed as parameter and will directly be used to perform the search I tried multiple solutions to what it meant by the object can be passed.

Things I Experimented

1.) I tried this, however it's giving me an IndexError: list index out of range error indicating that it has not found anything. I wonder why since the regex seems correct.

item = listWidget.findItems(r'\b'+'cat'+'\b',QtCore.Qt.MatchRegularExpression)[0]

2.) I tried this one still gives me this type of error.

File "finditems.py", line 7, in scrollitem = listWidget.findItems('cat',QtCore.Qt.MatchRegularExpression(QtCore.QRegularExpression(r'\b'+'cat'+'\b')))[0]
TypeError: 'MatchFlag' object is not callable

3.) Again I tried this one but I think I got it wrong since the first parameter of the findItems function needs to be a str type.

File "finditems.py", line 7, in scrollitem = listWidget.findItems(QtCore.QRegularExpression(r'\b'+'cat'+'\b'),QtCore.Qt.MatchRegularExpression)[0]
TypeError: findItems(self, str, Union[Qt.MatchFlags, Qt.MatchFlag]): argument 1 has unexpected type 'QRegularExpression'

How can I properly pass this QRegularExpression object as stated in the docs so that I can scroll to the string which has the EXACT WORD which is "cat"?

Answer

According to what you indicate, you want to find the words that contain the word cat, so you must use the following:

items = listWidget.findItems(r"\bcat\b", QtCore.Qt.MatchRegularExpression)
for item in items:print(item.text())

Output

1  cat
2  tom cat
4  dog and cat
5  super cat

Note: r'\b'+'cat'+'\b' is not r"\bcat\b" since the second \b is not escaped, so you must change it to r'\b'+'cat'+r'\b'


On the other hand, if the objective is to search for the next item then you must store the information of the previous item as the row and use that information to select the new item.

def scroll():new_item = Nonelast_selected_row = -1selected_items = listWidget.selectedItems()if selected_items:last_selected_row = listWidget.row(selected_items[0])items = listWidget.findItems(r"\bcat\b", QtCore.Qt.MatchRegularExpression)for item in items:if listWidget.row(item) > last_selected_row:new_item = itembreakif new_item:new_item.setSelected(True)listWidget.scrollToItem(new_item, QtWidgets.QAbstractItemView.PositionAtTop)
https://en.xdnf.cn/q/120200.html

Related Q&A

Python list rearrange the elements in a required order

My main list has 44 names as elements. I want to rearrange them in a specific order. I am giving here an example. Note that elements in my actual list are some technical names. No way related to what I…

GMB API accounts.locations.reviews.list

Can i get source code to get reviews using gmb python code also heard mybusiness is discontinued. I tried using my business api is discontinued can i get the implementation process to look for extract…

How to get words from an online text archive such as pastebin?

Im trying to get the words(users) from a text file hosted online, such as from www.site.com/mytextfile.txt or pastebin.com/raw/1111111. I will have multiple "users", one in each line. My code…

Python Histogram using matplotlib on top words

I am reading a file and calculating the frequency of the top 100 words. I am able to find that and create the following list:[(test, 510), (Hey, 362), ("please", 753), (take, 446), (herbert, …

how can I add field in serializer?

Below is my serializer.py file: from rest_framework import serializersclass TaskListSerializer(serializers.Serializer):id = serializers.CharField()user_id = serializers.CharField()status = serializers.…

Read and write a variable in module A from module B

Need a solution or workaround to read and write the variable in moduleA from moduleB please. Here is the code:moduleAimport moduleBvariable = 10def changeVariable():global variablevariable = 20def main…

Iterate through a pandas dataframe to get a specific output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 1 year ago.The comm…

Detect if you click inside a box in Python Zelle graphics

I have created a dice betting game. When my code is run, there is a "CLICK TO ROLL" button. Currently, if you click anywhere on the screen, the dice will roll. How can I make it so the progra…

Nested Triangle in Python

My assingmentAt each level the complete triangle for the previous level is placed into an extra outer triangle. The user should be asked to input the two characters to be used and the width of the inne…

How to fix cannot open file Test.py: [Errno2] No such file or directory?

I tried to run a python script which does not exist in current folder, for exampleC:\>python Test.pypython:cant open file Test.py:[Errno2] No such file or directoryI have to specify the absolute pat…