PyQt5-QComboBox,填充QQueryModel,包括Id;Name;.etc字段。使用名称作为QComboBox.modelColumn. 希望从单击的项目中检索id字段。在
我前后移动了模型列,但没有做任何好事。我还访问了QQueryModel.record发现它总是在第一张唱片上,而不是在当前唱片上。在
import MySQL_Connector
import sys
from PyQt5.QtCore import QVariant, Qt
from PyQt5.QtSql import QSqlDatabase, QSqlQueryModel,QSqlQuery , QSqlTableModel, QSqlError, QSqlQueryModel, QSqlQuery
from PyQt5.QtWidgets import QApplication, QMainWindow
from MainUI import Ui_MainWindow
class QConnectionError(Exception):
pass
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setupUi(self)
#setup Qsql databaase objects
cnn = MySQL_Connector.MysqlConnection('config.ini')
con_string = cnn.read_db_config()[1]
try:
db = QSqlDatabase.addDatabase("QMYSQL")
db.setHostName(con_string['host'])
db.setUserName(con_string['user'])
db.setDatabaseName(con_string['database'])
db.setPassword(con_string['password'])
ok = db.open()
if not ok:
raise QConnectionError("Connection failed--- Is the server running?")
except QConnectionError as err:
print("You'll have to wait until a connection is established")
return
finally:
if db.isOpen():
db.close()
self.qdb = db
self.qdb.open()
# set combobox
self.comboQuery = combo_query(self.qdb)
self.comboModel = QSqlQueryModel()
self.comboModel.setQuery(self.comboQuery)
self.comboBox.setModel(self.comboModel)
self.comboBox.setModelColumn(1)
self.comboBox.activated[int].connect(self.do_action)
#populate textView
self.query = test(self.qdb)
self.model = QSqlQueryModel()
self.model.setQuery(self.query)
self.model.setHeaderData(0,Qt.Horizontal, "ID")
self.model.setHeaderData(1, Qt.Horizontal, "Nombre")
self.tableView.rowHeight(2)
self.tableView.fontMetrics()
self.tableView.setModel(self.model)
self.show()
if self.qdb.isOpen():
self.qdb.close()
def do_action(self, str): #Experimenting
print(str, type(str))
self.tableView.selectRow(5)
def main():
app = QApplication(sys.argv)
window = MainWindow()
app.exec()
需要关于如何前进的建议。我使用的所有数据库都是基于ID字段的,无论出于什么原因,我都需要进一步查询。也许换个工具?另一种方法。在
QCombobox有两个适合您需要的信号:
activated()
在用户选择项目时发送,即使选择没有更改,请参见{a1}currentIndexChanged()
如果当前索引被用户选择或以编程方式更改,请参阅QComboBox.currentIndexChanged()两个信号都通过当前索引。 使用此索引,您可以通过
QSqlQuery.data()
获得所需的数据。在下面是一个使用sqlite3的简单示例,我认为您可以将其调整为适合您的数据库:
这里是数据库的转储tc.db公司名称:
^{pr2}$相关问题 更多 >
编程相关推荐