Pyside: используйте кнопку для копирования текста из qlineEdit в метку и в строку var - PullRequest
0 голосов
/ 13 декабря 2011

Я пытаюсь получить кнопку pyside для копирования текста из поля qlineEdit в метку и в строковую переменную.Я прошел почти все учебные пособия по Zetcode, но, очевидно, мне здесь не хватает чего-то критического.Будьте нежны, я новичок в питоне и новичок в писайде.Я ищу другие учебники по pyside.

Я попытался с помощью 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()

Ответы [ 3 ]

2 голосов
/ 13 декабря 2011

Существует несколько проблем, связанных с размещенным вами сценарием:

  1. author_label и qle ссылаются вне метода initUI, поэтому их необходимо заменить на self.author_label и self.qle везде, где они используются.
  2. Метод onChanged пытается получить текст редактирования строки, используя несуществующий метод getText.Используйте self.qle.text(), или, что еще лучше, используйте аргумент text, который передается методу onChanged с помощью сигнала textChanged.
  3. Метод sendtxt2_qle имеет ошибки, аналогичные (2), а также ошибочно пытается ссылаться на qle и author_label как атрибуты self.grid (который не существует).См. (1), как это исправить.

Примечание: Когда я запустил исправленную версию вашего скрипта, я получил несколько искаженных выводов из операторов печати.Это похоже на ошибку в PySide, потому что тот же скрипт отлично работает с PyQt4.(Я использую PySide-1.09.)

1 голос
/ 21 февраля 2013

Я понимаю, что эта тема некро, но хотела обновить для новых пользователей. Старый файл os.path теперь является подпроцессом (подпроцесс импорта).

Я столкнулся с этой проблемой, пытаясь передать QString в вызов подпроцесса, и наткнулся на ответ.

Используйте str(object.displayText()) для преобразования Qstring в String.

string = str(self.lineEdit.displayText())   
print string
0 голосов
/ 19 декабря 2011

Вот как я реализовал полезный ответ от эхуморо:

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