PYQT:如果选择了组合框中的项目,则设置lineedit的文本

2024-06-16 11:52:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题: 如果选择了ADuser,如何用“employeeID”填充lineedit中的文本?

我正在做的是:我从python运行一个PS脚本,它为我获取aduser,然后从PS脚本中获取输出(基本上是广告用户)并将其填充到一个组合框中(大约500个“items”)。在

Python代码(已编辑):

# NOTE: this is not the full code, just the full code for solving the problem
def __init__(self):
    super().__init__()
    self.__initUI__()

def __initUI__(self):
    self.vorgesetzter()
    self.persnum_supervisor()
    self.fill_the_combo_box()
    self.Vorgesetzte.currentIndexChanged.connect(self.display_employee_id)

def fill_the_combo_box(self):
    """Filling the combo box with the names extracted from a file."""

    subprocess.Popen(["powershell.exe", "C:\\Users\\User\\Desktop\\Get-ADUser.ps1"], stdout=subprocess.PIPE, universal_newlines=True, shell=True).communicate()

    lines = open('C:\\Users\\User\\Desktop\\users.txt').readlines()
    open('C:\\Users\\User\\Desktop\\newusers.txt', 'w').writelines(lines[3:])

    with open("C:\\Users\\User\\Desktop\\newusers.txt", 'r', encoding='utf8') as f:
          content = f.readlines()
          for line in content:
               tokens = line.split()
               if len(tokens) < 2:
                   continue # <--- skip the empty line of the file
               tostring = tokens[0] + " " + tokens[1] # <--- this is the full name
               self.Vorgesetzte.addItems([tostring])


def display_employee_id(self):
    """Checking whether the currently selected combo box name has an employeeID stored in the file."""

    with open("C:\\Users\\User\\Desktop\\users.txt", 'r', encoding='utf8') as f:
          selected_name = self.Vorgesetzte.currentText()
          content = f.readlines()
          for line in content:
               tokens = line.split()
               if len(tokens) < 2:
                   continue
               full_name = tokens[0] + " " + tokens[1]
               employeeID = str(tokens[2]) if len(tokens)==3 else "no id found!" # <-- support for absence of employeeID in the file, put whatever string you like here

               if selected_name == full_name:
                   self.persnum_supervisor.setText(employeeID)
                   break

def vorgesetzter(self):
    """Eingabefeld für den Vorgesetzten"""
    self.Vorgesetzte = QComboBox(self)
    self.Vorgesetzte.setEditable(True)
    self.Vorgesetzte.completer()

    font = self.Vorgesetzte.font()
    font.setPointSize(9)
    self.Vorgesetzte.setFont(font)

    self.Vorgesetzte.setFixedSize(250, 20)
    self.Vorgesetzte.move(150, 210)

    self.VorgesetzteBlock = QLabel(self)
    self.VorgesetzteBlock.move(10, 210)
    self.VorgesetzteBlock.setText("Vorgesetzte/r:")

def personalnum_supervisor(self):

    """TEXTLINE FÜR PERSONALNUMMER SUPERVISOR"""
    self.persnum_supervisor = QLineEdit(self)
    self.persnum_supervisor.setMaxLength(20)

    font = self.persnum_supervisor.font()
    font.setPointSize(9)
    self.persnum_supervisor.setFont(font)

    regex = QRegularExpression('^\d\d\d\d\d\d')
    validsuper_vis = QRegularExpressionValidator(regex)
    self.persnum_supervisor.setValidator(validsuper_vis)

    self.persnum_supervisor.move(750, 300)
    self.persnum_supervisor.setFixedSize(250, 20)

    self.persnum_supervisorBlock = QLabel(self)
    self.persnum_supervisorBlock.move(500, 300)
    self.persnum_supervisorBlock.setText("Personalnummer(Vorgesetzter):")


app = QApplication(sys.argv)
w = MainWindow()
sys.exit(app.exec_())

所以我接下来要做的是:如果在组合框中选择了广告用户,我需要用他的'employeeID'属性在lineedit中设置文本。在

以下Powershell代码:

^{pr2}$

在用户.txt文件(我不能给你看我们员工的名字所以我编辑了一下):

 name                       employeeID
 ----                       ----------
 forename surname            110001    
 forename surname            110002    
 forename surname            110003    
 forename surname            110004    
 forename surname            110005    
 forename surname            110006    

我很感激你的帮助!在


Tags: thenameselfdefsurnameusersfullfont
1条回答
网友
1楼 · 发布于 2024-06-16 11:52:05

现在您将employeeID存储在文件中,这样就更容易解决问题了。在

我修改的内容显示在评论中。在

from PyQt5 import QtWidgets,QtGui,QtCore
import sys
import subprocess

class Widget(QtWidgets.QWidget):

    def __init__(self,parent=None):
        super(Widget,self).__init__(parent=None)

        self.cbox = QtWidgets.QComboBox(self)
        self.setGeometry(100,100,300,300)
        self.fill_the_combo_box()

        self.lineEdit = QtWidgets.QLineEdit(self)
        self.lineEdit.setGeometry(100,100,100,100)
        self.cbox.currentIndexChanged.connect(self.display_employee_id) # will trigger every time you select a new name in the combo box.


    def fill_the_combo_box(self):
        """Filling the combo box with the names extracted from a file."""

        subprocess.Popen(["powershell.exe", "C:\\Users\\USER\\Desktop\\Get-ADUser.ps1"], stdout=subprocess.PIPE, universal_newlines=True, shell=True).communicate()

        lines = open('C:\\Users\\USER\\Desktop\\users.txt').readlines() 
        open('C:\\Users\\USER\\Desktop\\newusers.txt', 'w').writelines(lines[3:])

        with open("C:\\Users\\USER\\Desktop\\newusers.txt", 'r', encoding='utf8') as f:
              content = f.readlines()
              for line in content:
                   tokens = line.split()
                   if len(tokens) < 2:
                       continue # < - skip the empty line of the file
                   tostring = tokens[0] + " " + tokens[1] # < - this is the full name
                   tostringcleared = tostring.replace("[", "").replace("'", "").replace('\\ufeff',"").replace("]", "").replace(",", "")           #clear the strings from special characters
                   self.cbox.addItems([tostringcleared])


    def display_employee_id(self):
        """Checking whether the currently selected combo box name has an employeeID stored in the file."""

        with open("C:\\Users\\USER\\Desktop\\users.txt", 'r', encoding='utf8') as f:
              selected_name = self.cbox.currentText()
              content = f.readlines()  
              for line in content:
                   tokens = line.split()
                   full_name = tokens[0] + " " + tokens[1]
                   employeeID = str(tokens[2]) if len(tokens)==3 else "no id found!" # <  support for absence of employeeID in the file, put whatever string you like here

                   if selected_name == full_name:
                       self.lineedit.setText(employeeID)
                       break


if __name__ == "__main__":
    app =    QtWidgets.QApplication(sys.argv)

    widget = Widget()
    widget.show()
    sys.exit(app.exec_())

有两点需要注意:

  • 不支持重复项。如果您多次使用相同的名称,但使用不同的employeeID,则行edit将采用遇到的第一个名称的值(如果删除break),则使用最后一个名称的值。但是如果你的文件有重复的问题。

  • 也许你想保留标题,我们可以用这个跳过前两行:

一。在

^{pr2}$

相关问题 更多 >