如何通过双击在 qtablewidget 中编辑水平标题的标签?到目前为止我有什么但不起作用。因此,当有人双击顶部标题时,会弹出一个 linedit 允许输入文本,然后重置标签。
import sys
from PyQt4 import QtGui,QtCore
import generate_file
class WebGetMain(QtGui.QMainWindow,generate_file):
def __init__(self,parent=None):
super(WebGetMain,self).__init__(parent)
self.setupUi(self)
#set these values customizable before user populates the table
self.row_count = 20
self.col_count = 20
#setup actual cols,rows
self.web_get_table.setRowCount(self.row_count)
self.web_get_table.setColumnCount(self.col_count)
#allow horizontal header to be altered
#create and initialize linedit
self.linedit = QtGui.QLineEdit(parent=self.web_get_table.viewport())
self.linedit.setAlignment(QtCore.Qt.AlignTop)
self.linedit.setHidden(True)
self.linedit.editingFinished.connect(self.doneEditing)
#connect double click action on header
self.web_get_table.connect(self.web_get_table.horizontalHeader(),QtCore.SIGNAL('sectionDoubleClicked(int)'),self.on_header_doubleClicked)
#setup vertical scrollbars for adding rows
self.vBar = self.web_get_table.verticalScrollBar()
self._vBar_lastVal = self.vBar.value()
#initialize cols,rows
for column in range(0, 2):
for row in range(0, 3):
print row, column
item = QtGui.QTableWidgetItem()
self.web_get_table.setItem(row, column, item)
#scrollbar value signal to detect for scrolling
self.vBar.valueChanged.connect(self.scrollbarChanged)
def scrollbarChanged(self, val):
#initialize scrollbar
bar = self.vBar
minVal, maxVal = bar.minimum(), bar.maximum()
avg = (minVal+maxVal)/2
rowCount = self.web_get_table.rowCount()
# scrolling down
if val > self._vBar_lastVal and val >= avg:
self.web_get_table.insertRow(rowCount)
# scrolling up
elif val < self._vBar_lastVal:
lastRow = rowCount-20
empty = True
for col in xrange(self.web_get_table.columnCount()):
item = self.web_get_table.item(lastRow, col)
if item and item.text():
empty=False
break
if empty:
#remove rows when scrolling up
self.web_get_table.removeRow(lastRow)
self._vBar_lastVal = val
def doneEditing(self):
self.linedit.blockSignals(True)
self.linedit.setHidden(True)
oldname = self.web_get_table.model().dataset.field(self.sectionedit)
newname = str(self.linedit.text())
self.web_get_table.model().dataset.changeFieldName(oldname,newname)
self.linedit.setText('')
self.web_get_table.setCurrentIndex(QtCore.QModelIndex())
def on_header_doubleClicked(self,item):
self.linedit.setText(self.web_get_table.model().field(item).name)
self.linedit.setHidden(False)
self.linedit.blockSignals(False)
self.linedit.setFocus()
self.linedit.selectAll()
self.sectionedit = item
def main():
app = QtGui.QApplication(sys.argv)
app.setStyle(QtGui.QStyleFactory.create("Plastique"))
main_window = WebGetMain()
main_window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()