在我的示例程序中,我想在列表小部件中显示很多名称。在那儿,我想使用搜索按钮在列表小部件中搜索特定项目,然后在列表小部件中打印该项目名称。
下面是我的代码:
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
auto_search_vbox = QtGui.QVBoxLayout(self)
hbox=QtGui.QHBoxLayout()
le_search = QtGui.QLineEdit()
se_btn = QtGui.QPushButton("Search")
se_btn.clicked.connect(self.find_item)
hbox.addWidget(le_search)
hbox.addWidget(se_btn)
auto_search_vbox.addLayout(hbox)
self.listwidget = QtGui.QListWidget()
self.total_list =["machine","printer","xerox bundles"]
self.listwidget.addItems(self.total_list)
auto_search_vbox.addWidget(self.listwidget)
self.show()
def find_item(self):
out = self.listwidget.findItems("mac", QtCore.Qt.MatchExactly)
print out
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
答案 0 :(得分:2)
对不起,我有PyQt5。试试吧:
标记Qt :: MatchFlags
此枚举描述了在模型中搜索项目时可以使用的匹配类型。
import sys
#from PyQt4.QtGui import *
#from PyQt4.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.le_search = QLineEdit() # self. +++
se_btn = QPushButton("Search")
se_btn.clicked.connect(self.find_item)
self.listwidget = QListWidget()
self.total_list = ["machine", "mac1", "printer", "Printer","xerox bundles", "2mac"]
self.listwidget.addItems(self.total_list)
hbox = QHBoxLayout()
hbox.addWidget(self.le_search) # self. +++
hbox.addWidget(se_btn)
auto_search_vbox = QVBoxLayout(self)
auto_search_vbox.addLayout(hbox)
auto_search_vbox.addWidget(self.listwidget)
def find_item(self):
# out = self.listwidget.findItems("mac", QtCore.Qt.MatchExactly) # ---
# out = self.listwidget.findItems(self.le_search.text(), Qt.MatchExactly)
out = self.listwidget.findItems(self.le_search.text(),
Qt.MatchContains | # +++
Qt.MatchCaseSensitive) # +++
print("out->", [ i.text() for i in out ] )
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())