PyQt5。在QTableView

时间:2019-07-04 18:58:54

标签: python pyqt5

尊敬的用户。我在QSqlTableView的数据库SQLite3中显示值时遇到问题。从代码中可以看到,我在数据库中的逗号后加载了3个字符的数字,但是通过在QSqlTableView中自动显示以使其在单元格中显示出现了QDoubleSpinBox并自动舍入了值最多2个字符。我可以重载QDoubleSpinBox或为此元素重新安装setDecimals还是在表中这样做以显示诸如real的值,请不要安装QDoubleSpinBox和通常的lineEdit吗?这是我的代码:

from PyQt5 import QtCore, QtGui, QtWidgets, QtSql
import sys
import sqlite3

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, parent = None):
        super().__init__()
        self.initUI()

        self.create_table()
        self.open_table()             

    def initUI(self):

        self.my_dbtable_view = QtWidgets.QTableView(self)
        self.my_dbtable_view.resize(490,200)
        self.my_dbtable_view.move(5,5)

        self.setGeometry(300, 300, 500, 210)
        self.setWindowTitle('Title')        
        self.show()    

    def create_table(self):
        connect = sqlite3.connect('test.db')
        cursor = connect.cursor()
        try:
            cursor.execute('CREATE TABLE test_table (lenght REAL)')
            new_list = [round(x * 0.001, 3) for x in range(1500000,1500500)]
            for elem in new_list:
                cursor.execute('INSERT INTO test_table VALUES({0})' .format(elem))
                connect.commit()
            cursor.close()
            connect.close()                
        except sqlite3.OperationalError:
            pass




    def open_table(self):
        self.con = QtSql.QSqlDatabase.addDatabase('QSQLITE')
        self.con.setDatabaseName(r'.\test.db')
        self.con.open()  

        self.stm = QtSql.QSqlTableModel(parent = None)
        self.stm.setTable('test_table')
        self.stm.setSort(1, QtCore.Qt.AscendingOrder)
        self.stm.select()

        self.stm.setHeaderData(0, QtCore.Qt.Horizontal, 'Lenght')
        self.my_dbtable_view.setModel(self.stm)  
        self.my_dbtable_view.setColumnWidth(0, 100)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    myapp = MainWindow()
    sys.exit(app.exec_())

0 个答案:

没有答案