1 回答
TA贡献1859条经验 获得超6个赞
问题可能是线路self.tbox1.setFocus()导致focusChanged信号再次发射。QListWidget 被清除并重新进货,因此没有当前项目文本,文本框设置为空字符串,给人一种“无响应”的感觉。无论如何,我在尝试运行代码时遇到了分段错误,所以我不得不更改它。
所有的信号和槽连接都可以在主类中完成。从 QListWidget 中选择一个项目可以用currentTextChanged信号检测。在 focusChanged 上,保持指向最新聚焦的 QLineEdit 的指针。现在,当从列表小部件中选择一个项目时,您可以将文本设置为正确的文本框并重新对其应用焦点。
import sys
from PyQt5.QtWidgets import *
textbox_items = {
"textbox1": ["Red", "Green", "Blue", "Brown", "White", "Black", "Grey",
"Dark Red", "Dark Green", "Dark Blue"],
"textbox2": ["Gold", "Silver", "Bronze", "Copper", "Iron", "Aluminium",
"Taitanium"],
"textbox3": ["Indian Ocean", "Arabian Sea", "Bay of Bengal", "Black Sea",
"Pacific Ocean"]
}
class Mclick_sample_main(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Mouse click Samples")
self.textbox1 = QLineEdit()
self.textbox2 = QLineEdit()
self.textbox3 = QLineEdit()
self.listbox1 = QListWidget()
self.listbox1.currentTextChanged[str].connect(self.update_textbox)
self.textbox1.setObjectName("textbox1")
self.textbox2.setObjectName("textbox2")
self.textbox3.setObjectName("textbox3")
self.listbox1.setObjectName("listbox1")
vbox = QVBoxLayout(self)
vbox.addWidget(self.textbox1)
vbox.addWidget(self.textbox2)
vbox.addWidget(self.textbox3)
vbox.addWidget(self.listbox1)
self.current_textbox = None
QApplication.instance().focusChanged.connect(self.on_focusChanged)
def on_focusChanged(self, old, new):
if isinstance(new, QLineEdit) and new != self.current_textbox:
self.current_textbox = new
self.listbox1.clear()
self.listbox1.addItems(textbox_items[new.objectName()])
def update_textbox(self, text):
if text:
self.current_textbox.setText(text)
self.current_textbox.setFocus()
def main():
myapp = QApplication(sys.argv)
mywin = Mclick_sample_main()
mywin.show()
sys.exit(myapp.exec_())
if __name__ == "__main__":
main()
添加回答
举报