簡體   English   中英

PYQT:如果在組合框中選擇一個項目,則設置lineedit的文本

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

我的問題: 如果選擇了ADuser,如何用'employeeID'填充lineedit中的文本?

我正在做什么:我從python運行了PS腳本,這使我獲得了ADuser,然后從PS腳本(基本上是AD用戶)獲取了輸出,並將其填充到了一個組合框(大約500個“項”)中。

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

因此,我接下來需要做的是:如果在組合框中選擇了AD用戶,則需要在lineedit中使用“ employeeID”的AD用戶屬性設置文本。

下面的Powershell代碼:

$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文件(我無法向您顯示我們員工的姓名,這就是為什么我對其進行了一些編輯):

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

感謝您提供的幫助!

現在您將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,則行編輯將采用遇到的第一個(如果刪除break則為最后一個)的值。 但是,如果存在重復,則文​​件仍然存在問題。

  • 也許您想保留標題,我們可以使用以下方法跳過前兩行:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM