我是Python和PyQt的新手。我想知道如何使用PyQt连接到Postgresql,并将其显示在网格窗口中。我在用Qt设计师。有人能帮我吗?谢谢。
向你问好,尼森
发布于 2012-08-01 05:59:46
PyQt有数据库支持(我个人没有使用它,所以我不能评论),但是如果您查看QDatabase,应该是非常简单的文档。如果应用程序的api总是可以访问Qt,那么这可能是最好的方法,因为它们还有一些映射到接口的附加模型。
另一种选择是使用Python (对象关系映射器),例如Django、SQLAlchemy或storm,并定义表的(模型),并将它们手动加载到设计器接口中。
我个人的做法是,我实际上已经构建了自己的ORM ORB和一个名为PyQt的扩展库ProjexUI。ORB库与Qt无关,因此可以在非Qt项目中使用,ProjexUI库包含有助于在Qt小部件中使用数据库记录的映射。
有关文档和更多信息,请参阅:http://www.projexsoftware.com
对于一个简单的示例,通过执行以下操作创建一个新的UI文件:
这将创建PyQt接口部分,接下来仍然需要将接口连接到数据库后端。如何使用ORB进行此操作的最简单示例是:
# import the projexui and orb libraries
import projexui
import orb
# import PyQt modules
import PyQt4.QtGui
import PyQt4.uic
# create our database model
class User(orb.Table):
__db_columns__ = [
orb.Column( orb.ColumnType.String, 'username' ),
orb.Column( orb.ColumnType.String, 'password' ),
orb.Column( orb.ColumnType.Boolean, 'isActive' )
]
# the above model will by default create a PostgreSQL table called default_user with
# the fields _id, username, password and is_active. All of this is configurable, but
# you should read the docs for more info
# create the database information
db = orb.Database('Postgres', DATABASE_NAME) # set your db name
db.setUsername(USER_NAME) # set your db user name
db.setPassword(PASSWORD) # set your password
db.setHost('localhost') # set your host
db.setPort(5432) # set your port
# register the database
orb.Orb.instance().registerDatabase(db)
# sync the datbase (this will create your tables, update columns, etc.)
# NOTE: this should not always be called, it is here as an example
db.sync( dryRun = False ) # dryRun will just output the SQL calls
#-----------------------------
# End Database Code
#-----------------------------
class ExampleDialog(QtGui.QDialog):
def __init__( self, parent = None ):
super(ExampleDialog, self).__init__(parent)
# load your UI file
PyQt4.uic.loadUi(UI_FILE, self) # use the UI_FILE you saved
# connect the tree to the model
self.uiOrbTREE.setTableType(User)
# that is all you have to do to link the tree to the model and vice-versa,
# this is the most simple example of how to do this - you can do more as far
# as linking queries and sorting and such, but you should read the docs on
# the site
# launch as an application
if ( __name__ == '__main__' ):
# always check for an existing application first!
app = None
if ( not QtGui.QApplication.instance() ):
app = QtGui.QApplication(sys.argv)
dialog = ExampleDialog()
dialog.show()
# execute the app if we created it
if ( app ):
app.exec_()https://stackoverflow.com/questions/11533473
复制相似问题