Clear TableView in PyQt

I am learning how to display data and tables using PyQt. Ultimately, I would like to have a table showing the contents of the database, but for now I’m just understanding some fundamental principles. I have a basic setup (inserted below) using Qt Designer with a set of buttons ("Create", "Add Row", "Add Column" and "Clear"). Create creates a dummy table with pretending data. All buttons work separately from the "Clear" button, and when I click on it, Python completely crashes and I have no error messages to start developing what is wrong.

My questions: 1) What am I doing wrong? 2) What can I do in the exception handling form to prevent this, so I can understand what went wrong in the future?

import sys
from sqlite3 import *
from PyQt4 import QtCore, QtGui, QtSql
from PyQt4.QtCore import *
from PyQt4.QtGui import *

from test_class import Ui_MainWindow

class StartQT4(QtGui.QMainWindow, QTableWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.createbutton,QtCore.SIGNAL("clicked()"),self.file_dialog)
QtCore.QObject.connect(self.ui.addrowbutton,QtCore.SIGNAL("clicked()"),self.add_row)
QtCore.QObject.connect(self.ui.addcollumnbutton,QtCore.SIGNAL("clicked()"),self.add_column)
QtCore.QObject.connect(self.ui.clearbutton,QtCore.SIGNAL("clicked()"),self.clear_table)

def add_row(self):
    self.ui.tableWidget.insertRow (0)       

def add_column(self):
    self.ui.tableWidget.insertColumn (0)

def clear_table(self):
    #This bit that won't seem to work in any combination!
    #self.ui.tableWidget.clearContents()
    self.ui.tableWidget.clear()
    #self.ui.tableWidget.setColumnCount(0)
    #self.ui.tableWidget.setRowCount(0)

def file_dialog(self):
    self.ui.textEdit.setText("Testing testing")
    self.ui.tableWidget.setColumnCount(3)
    self.ui.tableWidget.setRowCount(3)
    a = QTableWidgetItem("A")
    self.ui.tableWidget.setHorizontalHeaderItem (0, a)
    a = QTableWidgetItem("B")
    self.ui.tableWidget.setHorizontalHeaderItem (1, a)
    self.ui.tableWidget.setHorizontalHeaderItem (2, a)
    b = QTableWidgetItem("Test")
    self.ui.tableWidget.setItem(1,1,b)       

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = StartQT4()
    myapp.show()
    sys.exit(app.exec_())
+3
source share
2 answers

Is he "completely falling"? Without a stack trace and everything else? Hard to believe...

In any case, the PyQt4 documentation knows neither QTableView.clear nor QTableView.clearContents, but knows QTableView.clearSpans , which should do what you want.

+2
source

It may be late, but:

1) What am I doing wrong?

  • Any error can lead to failure, so I can not answer.

2) , , , ?

  • python . , - PyQT .

QTableView.

0

Source: https://habr.com/ru/post/1761012/


All Articles