简体   繁体   English

如何从PyQt4中的QTextEdit获取输入

[英]How to get input from QTextEdit in PyQt4

how do i solve the following problem i am unable to get text from QTextEdit and insert it into Database... 我如何解决以下问题,我无法从QTextEdit获取文本并将其插入数据库...

Code: 码:

import sys
import MySQLdb
#from PyQt4.QtCore import *
from PyQt4.QtGui import *

e1=None
e2=None

def window():
    app=QApplication(sys.argv)
    win=QWidget()
    win.setWindowTitle("Sample")
    vbox=QVBoxLayout()
    e1 = QTextEdit()
    e2 = QTextEdit()
    vbox.addWidget(e1)
    vbox.addWidget(e2)
    vbox.addStretch()
    b1=QPushButton("Tap it!")
    vbox.addWidget(b1)
    b1.clicked.connect(b1_action)
    win.setGeometry(100,100,200,50)
    win.setLayout(vbox)
    win.show()
    sys.exit(app.exec_())

def b1_action():
    print "Button Clicked"
    db = MySQLdb.connect('localhost', 'root', 'mysql', 'Tecoc354')
    cursor=db.cursor()
    x1=e1.toPlainText()
    x2=e2.toPlainText()
    print x1," ",x2," "
    #sql="create table Sample(addr varchar(10),name varchar(10))"
   # cursor.execute(sql)
    sql2="insert into Tecoc354.sample values(%s,%s)"%(x1,x2)
    cursor.execute(sql2)
    db.commit()
    db.close()

window()

The problem here is, that in b1_action() the variables e1 and e2 are not recognized as QTextEdit() . 这里的问题是,在b1_action() ,变量e1e2无法识别为QTextEdit() Just for educational purpose add the line print e1 to both functions. 仅出于教育目的,将行print e1添加到两个功能中。 You'll get: 你会得到:

<PyQt4.QtGui.QTextEdit object at 0x01DA7490>
none

printed from Window() and b1_action() . Window()b1_action()打印。 So you see, in b1_action() e1 is not a QTextEdit . 如此看来,在b1_action() e1不是QTextEdit e1 / e2 in Window() are not the same variables as e1 / e2 in b1_action() e1 / e2Window()是不相同的变量e1 / e2b1_action()

The shortest way to solve that is to make e1 and e2 global variables. 解决该问题的最短方法是使e1e2全局变量。 So first delete the lines 所以先删除行

e1=None
e2=None

and then define both variables as global inside of Window : 然后将两个变量都定义为Window内部的全局变量:

from PyQt4.QtGui import *

def window():
    global e1
    global e2
    app=QApplication(sys.argv)
    win=QWidget()
    win.setWindowTitle("Sample")
    vbox=QVBoxLayout()
    e1 = QTextEdit()
    e2 = QTextEdit()

You can find some useful information in this question and answers about global variables 您可以在此问题和有关全局变量的答案中找到一些有用的信息

Generally I would not recommend to build a GUI based on functions and global variables. 通常,我不建议基于函数和全局变量构建GUI。 Find a tutorial and learn how to use classes. 查找教程并学习如何使用类。 For example this one 例如这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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