Question

I'm trying to get a pyside button to copy text from a qlineEdit field to a label and to a string variable. I have been through almost all of the Zetcode tutorials, but obviously I am missing something critical here. Be gentle, I'm a python newbie and a pyside newbie. I'm looking for more pyside tutorials.

I tried using my Qbutton to copy the text from the lineEdit, and then in a fit of desperation, I tried xxxxxxx

Here's my code (any suggestions would be much appreciated, particularly with a link to where I can learn about what I needed to know):

Thank you for your help, Marc

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()
Was it helpful?

Solution

There are several issues with the script you posted:

  1. author_label and qle are referenced outside the initUI method, so they need to be replaced with self.author_label and self.qle wherever they are used.
  2. The onChanged method tries to retrieve the line-edit text using the non-existent method getText. Use self.qle.text(), or, better still, use the text argument that is passed to the onChanged method by the textChanged signal.
  3. The sendtxt2_qle method has similar errors to (2), and also wrongly tries to reference qle and author_label as attributes of self.grid (which does not exist). See (1) for how to fix this.

Note: When I ran the amended version of you script, I got some corrupted output from the print statements. This appears to be a bug in PySide, because the same script runs perfectly fine using PyQt4. (I'm using PySide-1.09.)

OTHER TIPS

I realize this thread is necro but wanted to update for newer users. The old os.path is now subprocess (import subprocess).

Ran into this problem myself trying to pass QString to a subprocess call and stumbled on the answer.

Use str(object.displayText()) to convert Qstring to String.

string = str(self.lineEdit.displayText())   
print string

the following is how I implemented the helpful answer from 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_())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top