我有一个框架,我可以动态添加线条点击工具按钮。我需要所有这些lineedits在信号textChanged
上使用我的自动完成器。
我不太明白该怎么做。我在研究lambda
可能有所帮助时看到了,但我无法做到。我想这是因为我很难理解这一切是如何运作的。我使用QtDesigner和this教程来制作GUI。我的代码有两个文件 - 第一个只有小部件:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(799, 424)
...
self.toolbutton_add_score = QtWidgets.QToolButton(self.groupbox_scores)
self.toolbutton_add_score.setObjectName("toolbutton_add_score")
self.layout_groupbox_scores.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.toolbutton_add_score)
self.frame_movies_scores = QtWidgets.QFrame(self.groupbox_scores)
self.frame_movies_scores.setObjectName("frame_movies_scores")
self.layout_frame_movies_scores = QtWidgets.QGridLayout(self.frame_movies_scores)
self.layout_frame_movies_scores.setObjectName("layout_frame_movies_scores")
self.lineedit_input_movie = QtWidgets.QLineEdit(self.frame_movies_scores)
self.lineedit_input_movie.setObjectName("lineedit_input_movie")
self.layout_frame_movies_scores.addWidget(self.lineedit_input_movie, 0, 0)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Рекомендательная система"))
...
在第二个中有我的功能:
class MyWin(QtWidgets.QMainWindow):
def __init__(self, parent = None):
QtWidgets.QWidget.__init__(self, parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
self.ui.lineedit_input_movie.textChanged.connect(self.autocomplete)
self.ui.toolbutton_add_score.clicked.connect(self.add_score_field)
def autocomplete(self):
cursor.execute("SELECT title FROM movies WHERE title LIKE '%%' || %s || '%%';", (self.ui.lineedit_input_movie.text(),))
it = cursor.fetchall()
strings = [item[0] for item in it]
completer = QtWidgets.QCompleter(strings, self)
self.ui.lineedit_input_movie.setCompleter(completer)
self.ui.lineedit_input_movie.show()
def add_score_field(self):
self.lineedit_input_movie = QtWidgets.QLineEdit(self.ui.frame_movies_scores)
self.lineedit_input_movie.setObjectName("lineedit_input_movie")
self.ui.layout_frame_movies_scores.addWidget(self.lineedit_input_movie, r, 0)
此处的代码仅适用于布局中的fires lineedit。我该怎么做才能使它适用于布局中的所有lineedits?
答案 0 :(得分:1)
您需要将其他字段放在列表中以保留其引用。目前你正在覆盖你现有的不好的领域。您还需要为每个新字段连接textChanged
信号。
class MyWin(QtWidgets.QMainWindow):
def __init__(self, parent = None):
self.score_fields = []
# ...
def add_score_field(self):
# Create a new Line Edi
new_lineedit = QtWidgets.QLineEdit(self.ui.frame_movies_scores)
new_lineedit.setObjectName("lineedit_input_movie")
# append it to your score_fields list
self.score_fields.append(new_lineedit)
# add it to your layout
self.ui.layout_frame_movies_scores.addWidget(new_lineedit, r, 0)
# connect your signal
new_lineedit.textChanged.connect(self.autocomplete)