gpt4 book ai didi

python - 从 QLineEdit 读取文本作为 Qmenu 选项的子菜单

转载 作者:太空宇宙 更新时间:2023-11-03 20:28:35 28 4
gpt4 key购买 nike

读取 QlineEdit 中的文本,它是 Qmenu 的一部分

如最初代码所示,我认为可以使用触发函数来确定更改的选项,然后读取文本。如果我能弄清楚如何从子菜单中使用 currenttext() 读取 QlineEdit,我可以检查用户是否在需要时更改了输入。

import sys
from PyQt5.QtWidgets import QMainWindow, QAction, QActionGroup, QMenu, QApplication, QLineEdit, QWidgetAction

class Example(QMainWindow):

def __init__(self):
super().__init__()
self.menubar = self.menuBar()
self.menubar.installEventFilter(self)
self.fileMenu = self.menubar.addMenu('&Circuit Set-Up')
self.populate()

self.setGeometry(300, 300, 300, 200)
self.show()


def triggered(self, action):
print(action.text())


def populate(self):

for m in range(3):

setattr(self,'impMenu'+str(m),QMenu('Channel'+str(m), self))

factors=['Enter Transducer Calibration Constant [default 1] = 1',
'Enter Gauge Factor [default 2] = 2',
'Passion Ratio [default 0.3] = 0.3']

for n in range(3):

ql = QLineEdit(factors[n])
ql.setMinimumWidth(350)
wAction = QWidgetAction(self)
wAction.setDefaultWidget(ql)
getattr(self,'impMenu'+str(m)).addAction(wAction)

self.fileMenu.addMenu(getattr(self,'impMenu'+str(m)))
setattr(self,'triggered'+str(m),self.triggered)
getattr(self,'impMenu'+str(m)).triggered.connect(getattr(self,'triggered'+str(m)))


if __name__ == '__main__':

app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

最佳答案

QLineEdit 位于菜单上方,如果用户更改了文本,则不会通知您,因此使用 QMenu/QAction 中的信息是没有效率的。如果您想在用户更改文本时获取文本,请使用 QLineEdit 信号。

import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QAction, QApplication, QLineEdit, QMainWindow, QMenu, QWidgetAction


class Example(QMainWindow):
def __init__(self):
super().__init__()
self.menubar = self.menuBar()
self.menubar.installEventFilter(self)
self.fileMenu = self.menubar.addMenu("&Circuit Set-Up")
self.populate()

self.setGeometry(300, 300, 300, 200)
self.show()

@pyqtSlot(str)
def onTextChanged(self, text):
print(text)

def populate(self):

factors = [
"Enter Transducer Calibration Constant [default 1] = 1",
"Enter Gauge Factor [default 2] = 2",
"Passion Ratio [default 0.3] = 0.3",
]

for m in range(3):
menu = QMenu("Channel{}".format(m), self)
self.fileMenu.addMenu(menu)
for n in range(3):
ql = QLineEdit(factors[n])
ql.setMinimumWidth(350)
ql.textChanged.connect(self.onTextChanged)
wAction = QWidgetAction(self)
wAction.setDefaultWidget(ql)
menu.addAction(wAction)


if __name__ == "__main__":

app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

关于python - 从 QLineEdit 读取文本作为 Qmenu 选项的子菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57654923/

28 4 0