QRegularExpression 如何传递给 Qt::MatchRegularExpression [英] How QRegularExpression can be passed to Qt::MatchRegularExpression

查看:133
本文介绍了QRegularExpression 如何传递给 Qt::MatchRegularExpression的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试

现在我已经阅读了这个Qt::MatchRegularExpression &我希望用它来实现我的目标,即滚动到带有 EXACT WORD 的字符串,其中 包含 cat".基于它在这里说的文档.

Qt::MatchRegularExpression

<块引用>

使用正则表达式作为基于字符串的匹配搜索词.使用 QRegularExpression.使用此标志时,QRegularExpression 对象可以作为参数传递,并且会直接用于执行搜索.区分大小写的标志将是忽略,因为 QRegularExpression 对象预计将完全配置.这个枚举值是在 Qt 5.15 中添加的.

我似乎无法弄清楚这一点 QRegularExpression 对象可以作为参数传递,并将直接用于执行搜索 我尝试了多种解决方案来解决 object 可以通过.

我实验过的东西

1.) 我试过了,但是它给了我一个 IndexError: list index out of range 错误,表明它没有找到任何东西.我想知道为什么 regex 看起来是正确的.

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

2.) 我试过这个仍然给我这种类型的错误.

文件finditems.py",第7行,滚动item = listWidget.findItems('cat',QtCore.Qt.MatchRegularExpression(QtCore.QRegularExpression(r'\b'+'cat'+'\b')))[0]类型错误:MatchFlag"对象不可调用

3.) 我再次尝试了这个,但我认为我错了,因为 findItems 函数的第一个参数需要是 str 类型.

文件finditems.py",第7行,滚动item = listWidget.findItems(QtCore.QRegularExpression(r'\b'+'cat'+'\b'),QtCore.Qt.MatchRegularExpression)[0]TypeError: findItems(self, str, Union[Qt.MatchFlags, Qt.MatchFlag]): 参数 1 有意外类型 'QRegularExpression'

我如何正确pass这个QRegularExpression object如文档中所述,以便我可以滚动到具有EXACT WORD的字符串哪个是猫"?

解决方案

根据你的指示,你想找到包含cat这个词的词,所以你必须使用以下:

items = listWidget.findItems(r"\bcat\b", QtCore.Qt.MatchRegularExpression)对于项目中的项目:打印(项目.文本())

输出

1 只猫2 汤姆猫4 狗和猫5 超级猫

注意: r'\b'+'cat'+'\b' 不是 r"\bcat\b" 因为第二个 \b 没有转义,所以你必须把它改成 r'\b'+'cat'+r'\b'


另一方面,如果目标是搜索下一个项目,那么您必须将前一个项目的信息存储为行,并使用该信息选择新项目.

def scroll():new_item = 无last_selected_row = -1selected_items = listWidget.selectedItems()如果 selected_items:last_selected_row = listWidget.row(selected_items[0])items = listWidget.findItems(r"\bcat\b", QtCore.Qt.MatchRegularExpression)对于项目中的项目:如果 listWidget.row(item) >last_selected_row:new_item = 项目休息如果新项目:new_item.setSelected(True)listWidget.scrollToItem(new_item, QtWidgets.QAbstractItemView.PositionAtTop)

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 string

Input: 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,QtWidgets

app=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_()

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 scroll
    item = 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 scroll
    item = 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"?

解决方案

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 = None
    last_selected_row = -1
    selected_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 = item
            break
    if new_item:
        new_item.setSelected(True)
        listWidget.scrollToItem(new_item, QtWidgets.QAbstractItemView.PositionAtTop)

这篇关于QRegularExpression 如何传递给 Qt::MatchRegularExpression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆