简体   繁体   中英

PYQT: Set text of lineedit if an item in combobox is selected

My Question: How can I fill the text in a lineedit with the 'employeeID' if the ADuser is selected?

What I am doing: I run a PS script from python, which gets me the ADusers, then I take the Output from the PS-Script (the AD-Users basically) and fill it into a Combobox (around 500 'items').

Python code(Edited):

# 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_())

So what I need to do next is: If the AD-User is selected in the Combobox, I need to set the text in a lineedit with the AD-Users attribute of his 'employeeID'.

Powershell code below:

$s = "OU=,DC=,DC="
$User = Get-ADUser -Filter * -Properties name, employeeID -Searchbase $s | 
Select-Object -Property name,employeeID          
$User | Sort-Object -CaseSensitive | Out-File -Encoding utf8 C:\Users\USER\Desktop\users.txt

Users.txt file (I cant show you the names of our employees thats why I edited it a bit):

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

I appreciate any help how this might work !

Now that you store the employeeID in the file, it is easier to solve.

What I modified is shown in comments.

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_())

Two things to note:

  • Duplicates are not supported. If you have the same name several times but with different employeeID, the line edit will take the value of the first one encountered (or the last one if you remove the break ). But if there are duplicates that's an issue with your file anyway.

  • Maybe you want to keep the headers we can skip the two first lines using this:

.

for n, line in enumerate(content):
    if n<2:
        continue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM