本文介绍了PyQt - SQLAlchemy 不接受 QString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 PyQt 和 SQLAlchemy,而 SQLAlchemy 不接受 QStrings.有没有办法将 QStrings 传递给它,或者我每次都必须将 QStrings 转换为 Python 字符串?
I'm using PyQt and SQLAlchemy and SQLAlchemy doesn't accept QStrings. Is there any way to pass QStrings to it or I have to convert QStrings to Python strings every single time?
谢谢.
代码如下:
import sip
sip.setapi('QString', 2)
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, Float, MetaData, ForeignKey
from sqlalchemy.sql import select, and_
from PyQt4 import QtGui, QtCore
class DbUtils(object):
def __init__(self, db_file = None, parent = None):
self.db = None
self.db_connection = None
self.db_file = str(db_file)
def db_open(self):
self.db = create_engine('sqlite:///' + self.db_file)
self.db_connection = self.db.connect()
def db_close(self):
self.db_connection.close()
def db_create_voltdrop(self):
metadata = MetaData()
tb_cable_brands = Table('cable_brands', metadata,
Column('id', Integer, primary_key=True),
Column('brand', String)
)
tb_cable_types = Table('cable_types', metadata,
Column('id', Integer, primary_key=True),
Column('brand_id', None, ForeignKey('cable_brands.id')),
Column('type', String),
Column('alpha', String)
)
tb_cable_data = Table('cable_data', metadata,
Column('id', Integer, primary_key=True),
Column('type_id', None, ForeignKey('cable_types.id')),
Column('size', String),
Column('resistance', Float)
)
metadata.create_all(self.db)
def delete_cable_brand(self, cable_brand):
cable_brand = str(cable_brand)
metadata = MetaData()
metadata.bind = self.db
tb_cable_brands = Table('cable_brands', metadata, autoload = True)
cable_brands = select([tb_cable_brands.c.brand],
and_(tb_cable_brands.c.brand == cable_brand)
)
row = self.db_connection.execute(cable_brands)
data = row.fetchone()
if str(data[0]) == cable_brand:
cable_brands = tb_cable_brands.delete().where(tb_cable_brands.c.brand == cable_brand)
self.db_connection.execute(cable_brands)
return True
else:
return False
推荐答案
您可以 将 API 更改为 v2 并且 PyQt 将始终使用常规 Python 字符串而不是 QString
s.
You can change the API to v2 and PyQt will always use regular Python strings instead of QString
s.
编辑
案例 1:没有 sip.setapi
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
c = QtGui.QComboBox()
c.addItems(["one","two"])
print c.currentText(), type(c.currentText())
c.show()
sys.exit(app.exec_())
# Outputs
one <class 'PyQt4.QtCore.QString'>
案例 2:使用 sip.setapi
import sip
sip.setapi("QString",2)
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
c = QtGui.QComboBox()
c.addItems(["one","two"])
print c.currentText(), type(c.currentText())
c.show()
sys.exit(app.exec_())
# Outputs
one <type 'unicode'>
这篇关于PyQt - SQLAlchemy 不接受 QString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!