2011-12-12 69 views
0

我試圖讓pyside按鈕將文本從qlineEdit字段複製到標籤和字符串變量。我經歷了幾乎所有的Zetcode教程,但顯然我在這裏錯過了一些重要的東西。溫柔一點,我是一個蟒蛇新手,一個新手。我正在尋找更多pyside教程。Pyside:使用按鈕將文本從qlineEdit複製到標籤和字符串var

我試着用我的Qbutton從lineEdit複製文本,然後在一個合適的絕望中,我試圖XXXXXXX

這裏是我的代碼(任何建議,將不勝感激,尤其是帶有鏈接的地方,我可以瞭解我需要知道)什麼:

感謝你的幫助,馬克

import sys 
from PySide import QtGui, QtCore 

class Example(QtGui.QWidget): 
    def __init__(self): 
     super(Example, self).__init__()   
     self.initUI() 

    def initUI(self): 
     nu_prg_name_label = QtGui.QLabel('Program Name:') 
     author_label = QtGui.QLabel('Author') 

     qle = QtGui.QLineEdit(self) 
     qle.textChanged[str].connect(self.onChanged) 

     # I added the buttons 
     okButton = QtGui.QPushButton("OK") 
     cancelButton = QtGui.QPushButton("Cancel") 

     grid = QtGui.QGridLayout() 
     grid.setSpacing(4) 

     # (arg__1, row, column, rowSpan, columnSpan[, alignment=0]) 
     grid.addWidget(nu_prg_name_label, 1, 0) 
     grid.addWidget(author_label, 2, 0) 
     grid.addWidget(qle, 1, 1, 1, 4) 

     # I added the following 2 lines 
     grid.addWidget(okButton, 3, 3) 
     grid.addWidget(cancelButton, 3, 4) 
     #grid.addWidget(review_label, 3, 0) 

     # The QPushButton has a predefined 'signal' called 'clicked' 
     # which is triggered every time that the button is pressed. 
     # We will just 'connect' this signal to the sayHello() function: 
     # Connect the button to the function 
     okButton.clicked.connect(self.sendtxt2_qle) 

     #grid.addWidget(author_label, 2, 0) 
     #grid.addWidget(author_LineEdit02, 2, 1) 

     #grid.addWidget(review_label, 3, 0) 
     #grid.addWidget(review_TextEdit, 3, 1, 5, 1) 

     self.setLayout(grid) 

     # Horizontal, vertical, width, length 
     self.setGeometry(900, 300, 400, 100) 
     self.setWindowTitle('Create Dirs [Info, TestArea, ItWorks] for a Program')  
     self.show() 

    def onChanged(self, text):   
     nu_prg_name = self.qle.getText() 
     self.author_label.setText(nu_prg_name) 
     print "Line 67: nu_prg_name = " + nu_prg_name 

    def sendtxt2_qle(self): 
     nu_prg_name = self.grid.qle.getText() 
     self.grid.author_label.setText(nu_prg_name) 
     print "Line 72: nu_prg_name = " + nu_prg_name 

def main(): 
    app = QtGui.QApplication(sys.argv) 
    ex = Example() 
    sys.exit(app.exec_()) 

if __name__ == '__main__': 
    main() 

回答

2

有與您發佈的腳本幾個問題:

  1. author_labelqle是本initUI方法外引用的,所以他們需要與self.author_labelself.qle替換無論他們在哪裏使用。
  2. onChanged方法嘗試使用不存在的方法getText檢索行編輯文本。使用self.qle.text(),或者更好的辦法是使用textChanged信號傳遞給onChanged方法的參數text
  3. sendtxt2_qle方法與(2)類似的錯誤,也錯誤地嘗試引用qleauthor_label作爲self.grid(它不存在)的屬性。參見(1)瞭解如何解決這個問題。

注意:當我運行腳本的修正版本時,我從打印語句中得到了一些損壞的輸出。這似乎是PySide中的一個錯誤,因爲使用PyQt4時,相同的腳本運行得非常好。 (我使用PySide-1.09。)

0

以下是我是如何實現的有用的答案從ekhumoro:

""" 
     This script creates a new set of directories for a program/software. The directories 
    will include an info-directory, and MarcsPrgs-directories [ItWorks, TestArea] 
    where I will develop utilities/programs to work in that program/software. 

     This script also creates a 'hyperlink_doc_string', which will be implanted 
    into the office's html menu page. 
    """ 

    import os, sys, shutil #win32clipboard, win32con, 
    import re, string, traceback, pdb #easygui, 
    from PyQt4 import QtGui 
    from PyQt4 import QtCore 
    import win32clipboard 
    import time 
    import subprocess 

    def create_Html(nu_prg_name): 
     """ 
     This function creates a set of hyperlinks to the new directories. The hyperlinks will 
     1) appear in the Qt dialog window, 
      which is generated (below) by: 'class Example(QtGui.QWidget)' 
       and 
     2) be added to an html page 
     """ 

     if len(nu_prg_name) == 0: 
      print 'Error message fr "def create_dirs_and_Html(nu_prg_name)": ' \ 
       + ' The variable "nu_prg_name" is empty.' 


     hyperlink_doc_string = r'<a href="P:\Data\VB' + '\\' + nu_prg_name + '_Info' + '\\">' + nu_prg_name + '_Info</a>&nbsp;&nbsp;&nbsp;' \ 
      + '\n' + r'<a href="M:' + '\\' + nu_prg_name + '\">M-drv_Dir</a>&nbsp;&nbsp;' \ 
      + '\n' + r'<a href="P:\Data\VB' + '\\' + nu_prg_name + r'_Info\URLs' + '\\">' + nu_prg_name + r'_URLs</a><br />' \ 
      + '\n' + r'<a href="P:\Data\VB' + '\\' + nu_prg_name + r'_MarcsPrgs' + '\\">' + nu_prg_name + r'_MarcsPrgs</a>&nbsp;&nbsp;' \ 
      + '\n' + r'<a href="P:\Data\VB' + '\\' + nu_prg_name + r'_MarcsPrgs' + '\\' + nu_prg_name + r'_TestArea' + '\\">' + nu_prg_name + '_TestArea</a>&nbsp;&nbsp;' \ 
      + '\n' + r'<a href="P:\Data\VB' + '\\' + nu_prg_name + r'_MarcsPrgs' + '\\' + nu_prg_name + r'_ItWorks' + '\\">' + nu_prg_name + '_ItWorks</a>' \ 
      + '<br />\n' 

     print "Line 38: " + hyperlink_doc_string + '\n\n' 


     ex.sendtxt2_qle_test(hyperlink_doc_string) 

     ## Send the hyperlink_doc_string to the Windows clipboard 
     ## (this is a temporary solution; later I'll have the script add it directly to the ToolbarB) 
     # win32clipboard.OpenClipboard() 
     # win32clipboard.EmptyClipboard() 
     # win32clipboard.SetClipboardText(hyperlink_doc_string) 
     # win32clipboard.CloseClipboard() 

     # pdb.set_trace() 

     """ 
     The next line sends the hyperlink_doc_string to the dialog box, wherein 
     the hyperlink_doc_string will be viewed. If the hyperlink_doc_string 
     is approved, the user will click the 'OK' button, which calls 
     ex's internal function 'makeDirsAndHtml_ok'. 
     The 'makeDirsAndHtml_ok' function calls sequentially the following two 
     functions: 
      [1] 'create_Html(self.nu_prg_name_var)', and [2] 'create_dirs(nu_prg_name)' 

     """ 

     #ex.sendtxt2_qle_test(hyperlink_doc_string) 

     #ex.callMsgBoxFromOutsideThisClass() 

     # TODO: Add code that will implant the 'hyperlink_doc_string' into the office's html menu 

    # pdb.set_trace()# commands are n (next); c (continue); s (step thru) 
    #    print(var) 

     # create_dirs(nu_prg_name) 


    def writeHTML2file(hyperlink_doc_string, nu_prg_name): 
     # Save the hyperlink_doc_string to a file so that I can paste it into Toolbar B. 
     print 'Line 78: \nhyperlink_doc_string = ' + hyperlink_doc_string + '\n\n' \ 
      'nu_prg_name = ' + nu_prg_name 
     tmp_filename = 'tmp_' + nu_prg_name + '_' + str(time.time()) + '.txt' 
     tmp_filename = r"C:\Apps\E_drive" + '\\' + tmp_filename 
     fileobj = open(tmp_filename, 'w') 
     fileobj.write(hyperlink_doc_string) 
     fileobj.close() 


    def create_dirs(nu_prg_name): 
     """ 
     This function creates a new set of directories for a program/software. The directories 
     will include an info-directory, and MarcsPrgs-directories [ItWorks, TestArea] 
     where I will develop utilities/programs to work in that program/software. 
     """ 


     Archive_dot_Rar_file_FULLName = r"K:\data\FORMS\File folder setup forms\SAVE.and.Put.nothing.in.this.RarArchive.rar" 

     TopDir = r"P:\Data\VB" 

     hyperlink_doc_ls = ['M_drv_Dir', 'URLs'] 

     dirlist = ['_Info', '_MarcsPrgs', '_TestArea', '_ItWorks'] 

     numasterpath = TopDir + "\\" + nu_prg_name 

     dir_pathlist = dirlist[:] 


     for i in range(2): 
      dir_pathlist[i] = numasterpath + str(dir_pathlist[i]) 


     for i in range(2, 4): 
      dir_pathlist[i] = str(dir_pathlist[1]) + "\\" + nu_prg_name + str(dir_pathlist[i]) 

     # TO DO : CREATE A DIR FOR URLs 


     print '\n' + 'Line 60: ' + str(dir_pathlist) + '\n' 


     itms2chkexistence = [Archive_dot_Rar_file_FULLName, dir_pathlist[0], dir_pathlist[1]] # TopDir and numasterpath may be effectively 


     i = 0 

     int_dirs_whShd_not_exist = 2 

     if 1 == 1: 

      for item in itms2chkexistence: 
       # check to determine if critical items exist 
       # i.e., [0]=Archive_dot_Rar_file_FULLName, and [2]=TopDir 
       if i < 1: # Verify that these exist: [0]=Archive_dot_Rar_file_FULLName, and [2]=TopDir 
        if os.path.exists(item): 
         pass 
        elif os.path.isfile(item): 
         print 'Error message from Line 79 of "' + str(os.argv[0]) + ':\n"' \ 
          + item + '" does not exist. ' \ 
          + 'This script will now terminate.' 
         quit() 

       if i > 0: 

        #Verify that the following 2 dirs do NOT exist: 1) ' + nu_prg_name + '_Info 2) ' + nu_prg_name + '_MarcsPrgs 
        # because we don't want to over-write .rar files, or other things. 

        if os.path.exists(item): 
         print 'Line 90: Error! "' + item + '" already exists. ' + \ 
         'This script will now terminate.' 
     #    quit() 

        else: 
         print 'Line 95: int_dirs_whShd_not_exist (' + str(item) + \ 
          ') = ' + str(int_dirs_whShd_not_exist) 


        if os.path.isfile(item): 
         print 'Line 100: Error! "' + item + '" is a file that already exists. ' + \ 
         'This script will now terminate.' 
         quit() 

        else: 
         print 'Line 105: int_dirs_whShd_not_exist (' + str(item) + \ 
          ') = ' + str(int_dirs_whShd_not_exist) 

         int_dirs_whShd_not_exist = int_dirs_whShd_not_exist - 1 

         print 'Line 110: int_dirs_whShd_not_exist (' + str(item) + \ 
          ') = ' + str(int_dirs_whShd_not_exist) 
       i +=1 

      print 'Line 114: int_dirs_whShd_not_exist = ' + str(int_dirs_whShd_not_exist) 

      # Above, we verified that that the following 2 dirs do NOT exist: 
      #  1) ' + nu_prg_name + '_Info 2) ' + nu_prg_name + '_MarcsPrgs 
      # But I don't want to reprogram this, so I'll just check again. 


      nuRars = [str(dir + '\\Archive.Nu.rar') for dir in dir_pathlist] 
      print 'Line 122: "str(nuRars) = "' + '\n\t' + str(nuRars) 

      #pdb.set_trace() 

      if int_dirs_whShd_not_exist == 0: 

       print 'Success Message from Line 128 of "' + str(sys.argv[0]) + '":\n' \ 
        + 'dir_pathlist = ' + '\n\t' + str(dir_pathlist) + '\n\n' \ 
        + 'nuRars = ' + '\n\t' + str(nuRars) 

       path2open = '"' + str(dir_pathlist[0]) + '"' 
       print 'Line 191: path2open = ' + dir_pathlist[0] 

       #pdb.set_trace() 

       [os.mkdir(dir) for dir in dir_pathlist] 
      else: 
       print 'ERROR! Line 134: "int_dirs_whShd_not_exist" <> 0 ' 



      print 'Success Message from Line 138 of "' + str(sys.argv[0]) + '":\n' \ 
        + str(dir_pathlist) + '\n\n' 

      # pdb.set_trace() 
      for nurarfile in nuRars: 
       print 'Line 143: nurarfile = ' + str(nurarfile) + '\n' \ 
        + 'Archive_dot_Rar_file_FULLName = ' + str(Archive_dot_Rar_file_FULLName) \ 
        + '\n\n' 
       shutil.copyfile(Archive_dot_Rar_file_FULLName, str(nurarfile)) 
      #[shutil.copyfile(Archive_dot_Rar_file_FULLName, nurarfile) for nurarfile in nuRars] 


      # Verify success of job... 
      for rarAchiveFile in nuRars: 
       # check to determine if critical items exist 
       if os.path.exists(rarAchiveFile): 
        pass 
       else: 
        print "Error! " + Archive_dot_Rar_file_FULLName + "does not exist. " + \ 
        "The scriptfailed. I don't know why. This script will now terminate." 
        quit() 

      cmdline = r'explorer /select, ' + path2open 
      subprocess.Popen(cmdline) 

      strMsgBoxMsg = "Success! All directories and Rar Archive files have been created.\t" + \ 
      "Job done!" 

      os.system(r"C:\Apps\UtilitiesByMarc\MessageBoxe_SAVE_.vbs" + ' "' + strMsgBoxMsg + '"') 
      #subprocess.Popen(cmdline) 
      print strMsgBoxMsg 




    class Example(QtGui.QWidget): 

     def __init__(self): 
      super(Example, self).__init__() 

      self.initUI() 

     def initUI(self): 

      self.nu_prg_name_label = QtGui.QLabel('Program Name:') 
      self.author_label = QtGui.QLabel('') 

      self.qle = QtGui.QLineEdit(self) 
      #self.qle.textChanged[str].connect(self.onChanged) #This line worked fine, i think. 
      #self.connect(self.qle.textChanged[str],self.onChanged) 
      #self.qle.textChanged[str].connect(self.onChanged) 
      #self.connect(self.qle.textChanged(QString)),this,SLOT(onChanged(QString)) 

      # I added the buttons 
      self.testButton = QtGui.QPushButton("Test") 
      self.okButton = QtGui.QPushButton("OK") 
      self.cancelButton = QtGui.QPushButton("Cancel") 

      grid = QtGui.QGridLayout() 
      grid.setSpacing(4) 

      # (arg__1, row, column, rowSpan, columnSpan[, alignment=0]) 
      grid.addWidget(self.nu_prg_name_label, 1, 0) 
      grid.addWidget(self.author_label, 2, 0) 
      grid.addWidget(self.qle, 1, 1, 1, 4) 

      # I added the following 3 lines 
      grid.addWidget(self.testButton, 3, 2) 
      grid.addWidget(self.okButton, 3, 3) 
      grid.addWidget(self.cancelButton, 3, 4) 
      #grid.addWidget(review_label, 3, 0) 


      # The QPushButton has a predefined 'signal' called 'clicked' 
      # which is triggered every time that the button is pressed. 
      # We will just 'connect' this signal to the sayHello() function: 
      # Connect the button to the function 
      self.testButton.clicked.connect(self.sendtxt2_qle_test) 
      self.okButton.clicked.connect(self.makeDirsAndHtml_ok) 
      # qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit) 
      self.cancelButton.clicked.connect(QtCore.QCoreApplication.instance().quit) 

      #grid.addWidget(author_label, 2, 0) 
      #grid.addWidget(author_LineEdit02, 2, 1) 

      #grid.addWidget(review_label, 3, 0) 
      #grid.addWidget(review_TextEdit, 3, 1, 5, 1) 

      self.setLayout(grid) 

      # Horizontal, vertical, width, length 
      #self.setGeometry(10, 300, 400, 100) 
      self.setGeometry(10, 300, 400, 100) 
      self.setWindowTitle('Create Dirs [Info, TestArea, ItWorks] for a Program')  
      self.show() 

      self.bln_you_saw_test_results = False 


     def resize_win2hold_html(self): 

      # Horizontal, vertical, width, length 
      #self.setGeometry(10, 20, 800, 800) 
      self.setGeometry(10, 300, 400, 150) 
      self.setWindowTitle('Create Dirs [Info, TestArea, ItWorks] for a Program')  
      self.show() 


     def onChanged(self, text): 

      self.nu_prg_name_var = self.qle.text() 
      self.author_label.setText(self.nu_prg_name_var) 
      #print "Line 224: nu_prg_name_var = " + self.nu_prg_name_var 


     def sendtxt2_qle_test(self, HtmlStr="HTML"): 
      self.bln_you_saw_test_results = True 
      self.nu_prg_name_var = self.qle.text() 
      # os.system(r"C:\Apps\UtilitiesByMarc\MessageBoxe_SAVE_.vbs" + ' "' + 'Line 122 in sendtxt2_qle_test' + '"') 

      if HtmlStr == False: 
       create_Html(self.nu_prg_name_var) 

      if HtmlStr: 
       self.resize_win2hold_html() 
       self.msge = HtmlStr 
       self.author_label.setText(self.msge) 
       writeHTML2file(HtmlStr, self.nu_prg_name_var) 
      #print "Line 242: nu_prg_name_var = " + self.nu_prg_name_var 


     def makeDirsAndHtml_ok(self): 
      if self.bln_you_saw_test_results == False: 
       strMsgBoxMsg = 'You should try the "Test" button before you hit the "Ok" button.' 
       os.system(r"C:\Apps\UtilitiesByMarc\MessageBoxe_SAVE_.vbs" + ' "' + strMsgBoxMsg + '"') 
       #subprocess.Popen(cmdline) 
       print strMsgBoxMsg 
       return 
      else:      
       self.nu_prg_name_var = self.qle.text() 
       self.resize_win2hold_html() 
       self.author_label.setText(self.nu_prg_name_var) 
       create_Html(self.nu_prg_name_var) 
       create_dirs(self.nu_prg_name_var) 
      #print "Line 282: nu_prg_name_var = " + self.nu_prg_name_var 


     def callMsgBoxFromOutsideThisClass(self): 
      # strCmdLine = r"C:\Apps\UtilitiesByMarc\MessageBoxe_SAVE_.vbs" + ' "Hello from Line 137"' 
      #os.system(strCmdLine) 
      pass 


    def main():  
     app = QtGui.QApplication(sys.argv) 
     ex = Example() 
     sys.exit(app.exec_()) 


    if __name__ == '__main__': 
     #main() 
     app = QtGui.QApplication(sys.argv) 
     ex = Example() 
     sys.exit(app.exec_()) 
0

我意識到這線程是死靈,但希望更新新用戶。舊的os.path現在是子流程(導入子流程)。

自己試圖將QString傳遞給子進程調用並偶然發現答案,這個問題一直存在。使用str(object.displayText())將Qstring轉換爲字符串。

string = str(self.lineEdit.displayText()) 
print string 
相關問題