- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个QTreeView
它通过QSqlTableModel
显示来自SQLite的结果(PyQt5版本:5.13.0)。我想通过详细对话框更改一些值,该对话框通过 modelTable.record()
填充数据。因此我将编辑策略设置为OnManualSubmit
并稍后使用 submitAll()
存储这些值.
问题:我使用 record.setValue()
将更改后的值写入 Db 。但是:如果我更改一个值两次,当前行号可能会更改。
重现:
该条目将应用于最后一行。 -> 好的。
但是旧值仍然保留在第一行!现在我的第一行和最后一行完全相同,并且之前第一行的旧值丢失了!SQLite 错误 UNIQUE constraint failed: <id> Unable to fetch row
也会发生。
预期:第二次按“保存”时,对话框中的值将显示在最后一行,并且第 1 行中的旧值是正确的。
(如果您按下“刷新”按钮或关闭 2 个修改操作之间的 dlg,您就会得到此信息。)
完整的工作代码示例:
import sys
import re
from PyQt5 import QtWidgets, QtGui, QtCore, QtSql
TRACE = True
MY_TABLE = "person"
db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName(":memory:")
modelQuery = QtSql.QSqlQueryModel()
modelTable = QtSql.QSqlRelationalTableModel()
g_hits_count = 0
g_total_count = 0
g_selected_count = 0
def trace(message):
if TRACE:
print(message)
def _human_key(key):
parts = re.split(r'(\d*\.\d+|\d+)', key)
return tuple((e.swapcase() if i % 2 == 0 else float(e))
for i, e in enumerate(parts))
class dlgDetail(QtWidgets.QDialog):
def __init__(self, parent, cur_row, row_id):
QtWidgets.QDialog.__init__(self, parent)
self.setModal(False)
self.setWindowModality(QtCore.Qt.NonModal)
self.parent = self.parent()
trace(f"dlgDetail was called with cur_row: {cur_row}")
self.cur_row = cur_row
self.row_id = row_id
self.setupUi(self)
# connect signals
self.accepted.connect(self.dlgDetail_accepted)
self.rejected.connect(self.dlgDetail_rejected)
self.pbNew.clicked.connect(self.on_pbNew_clicked)
self.pbSave.clicked.connect(self.on_pbSave_clicked)
self.pbSave.setDefault(True)
self.pbDel.clicked.connect(self.on_pbDel_clicked)
self.pbCancel.clicked.connect(self.on_pbCancel_clicked)
if cur_row > -1: # existing record
# load selected record
# get current selection (could be filtered)
sourceIdx = self.parent.treeView.model().mapToSource(self.parent.treeView.currentIndex())
self.cur_row = sourceIdx.row()
trace(f"got my own cur_row -> {self.cur_row}")
record_display = modelTable.record(self.cur_row)
persId = record_display.value("persId")
lastName = record_display.value("lastName")
firstName = record_display.value("firstName")
country = record_display.value("name")
# display record
self.efId.setText(persId)
self.efLastName.setText(lastName)
self.efFirstName.setText(firstName)
self.populate_comboBox(self.cmbCountry, country)
else: # new record
# get next free row id
modelQuery.setQuery("SELECT IFNULL(MAX(id),0)+1 FROM person")
self.row_id = modelQuery.data(modelQuery.index(0, 0))
self.efId.setText("new" + str(self.row_id))
self.efLastName.setText("new" + str(self.row_id))
self.efFirstName.setText("new" + str(self.row_id))
self.populate_comboBox(self.cmbCountry, 0)
self.show()
def get_geometry(self):
return self.geometry().x(), self.geometry().y(), self.geometry().width(), self.geometry().height()
def center(self, offset):
frameGm = self.frameGeometry()
screen = QtWidgets.QApplication.desktop().screenNumber(QtWidgets.QApplication.desktop().cursor().pos())
centerPoint = QtWidgets.QApplication.desktop().screenGeometry(screen).center()
frameGm.moveCenter(centerPoint)
self.move(frameGm.topLeft()+QtCore.QPoint(frameGm.topLeft().x(), frameGm.topLeft().y()+offset))
def clear_inputs(self):
self.efId.setText("new")
self.efLastName.setText("new")
self.efFirstName.setText("new")
self.cmbCountry.setCurrentIndex(0)
def setupUi(self, parent):
vBox = QtWidgets.QVBoxLayout(self)
form = QtWidgets.QFormLayout()
lblId = QtWidgets.QLabel(self)
lblId.setText("ID:")
form.setWidget(0, QtWidgets.QFormLayout.LabelRole, lblId)
self.efId = QtWidgets.QLineEdit(self)
form.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.efId)
lblLastName = QtWidgets.QLabel(self)
lblLastName.setText("Last Name:")
form.setWidget(1, QtWidgets.QFormLayout.LabelRole, lblLastName)
self.efLastName = QtWidgets.QLineEdit(self)
form.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.efLastName)
lblFirstName = QtWidgets.QLabel(self)
lblFirstName.setText("First Name:")
form.setWidget(2, QtWidgets.QFormLayout.LabelRole, lblFirstName)
self.efFirstName = QtWidgets.QLineEdit(self)
form.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.efFirstName)
lblCountry = QtWidgets.QLabel(self)
lblCountry.setText("Country:")
form.setWidget(3, QtWidgets.QFormLayout.LabelRole, lblCountry)
self.cmbCountry = QtWidgets.QComboBox(self)
form.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.cmbCountry)
vBox.addLayout(form)
# command buttons
hBox = QtWidgets.QHBoxLayout()
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
hBox.addItem(spacerItem)
self.pbNew = QtWidgets.QPushButton(self)
self.pbNew.setText("New")
hBox.addWidget(self.pbNew)
self.pbSave = QtWidgets.QPushButton(self)
self.pbSave.setText("Save")
hBox.addWidget(self.pbSave)
self.pbDel = QtWidgets.QPushButton(self)
self.pbDel.setText("Del")
hBox.addWidget(self.pbDel)
self.pbCancel = QtWidgets.QPushButton(self)
self.pbCancel.setText("Cancel")
hBox.addWidget(self.pbCancel)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
hBox.addItem(spacerItem1)
vBox.addLayout(hBox)
def populate_comboBox(self, comboBox, country):
model = QtSql.QSqlTableModel()
model.setTable("country")
model.select()
comboBox.setModel(model)
comboBox.setModelColumn(model.fieldIndex("name"))
# select the person's set country
index = comboBox.findText(str(country), QtCore.Qt.MatchFixedString)
if index >= 0:
comboBox.setCurrentIndex(index)
def dlgDetail_accepted(self):
pass
def dlgDetail_rejected(self):
pass
@QtCore.pyqtSlot()
def on_pbCancel_clicked(self):
self.reject()
@QtCore.pyqtSlot()
def on_pbSave_clicked(self):
trace(f"saving for row_id: {self.row_id}")
country_id = self.cmbCountry.currentIndex()
self.cur_row, self.row_id = self.parent.update_record(self.cur_row, self.row_id, self.efId.text(), self.efLastName.text(), self.efFirstName.text(), country_id)
@QtCore.pyqtSlot()
def on_pbNew_clicked(self):
self.accept()
self.parent.new_record()
@QtCore.pyqtSlot()
def on_pbDel_clicked(self):
self.parent.del_record()
self.accept()
class FilterHeader(QtWidgets.QHeaderView):
filterActivated = QtCore.pyqtSignal()
def __init__(self, parent):
super().__init__(QtCore.Qt.Horizontal, parent)
self._editors = []
self._padding = 4
self.setStretchLastSection(True)
self.setDefaultAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
self.setSortIndicatorShown(False)
self.sectionResized.connect(self.adjustPositions)
parent.horizontalScrollBar().valueChanged.connect(self.adjustPositions)
def setFilterBoxes(self, count):
while self._editors:
editor = self._editors.pop()
editor.deleteLater()
for index in range(count):
editor = QtWidgets.QLineEdit(self.parent())
editor.setPlaceholderText('Filter')
editor.setClearButtonEnabled(True)
editor.textChanged.connect(self.textChanged)
self._editors.append(editor)
self.adjustPositions()
def textChanged(self):
self.filterActivated.emit()
def sizeHint(self):
size = super().sizeHint()
if self._editors:
height = self._editors[0].sizeHint().height()
size.setHeight(size.height() + height + self._padding)
return size
def updateGeometries(self):
if self._editors:
height = self._editors[0].sizeHint().height()
self.setViewportMargins(0, 0, 0, height + self._padding)
else:
self.setViewportMargins(0, 0, 0, 0)
super().updateGeometries()
self.adjustPositions()
def adjustPositions(self):
for index, editor in enumerate(self._editors):
height = editor.sizeHint().height()
editor.move(
self.sectionPosition(index) - self.offset() + 2,
height + (self._padding // 2))
editor.resize(self.sectionSize(index), height)
def filterText(self, index):
if 0 <= index < len(self._editors):
return self._editors[index].text()
return ''
def setFilterText(self, index, text):
if 0 <= index < len(self._editors):
self._editors[index].setText(text)
def clearFilters(self):
for editor in self._editors:
editor.clear()
class HumanProxyModel(QtCore.QSortFilterProxyModel):
def lessThan(self, source_left, source_right):
data_left = source_left.data()
data_right = source_right.data()
if type(data_left) == type(data_right) == str:
return _human_key(data_left) < _human_key(data_right)
return super(HumanProxyModel, self).lessThan(source_left, source_right)
@property
def filters(self):
if not hasattr(self, "_filters"):
self._filters = []
return self._filters
@filters.setter
def filters(self, filters):
self._filters = filters
self.invalidateFilter()
global g_hits_count
g_hits_count = self.rowCount()
def filterAcceptsRow(self, sourceRow, sourceParent):
for i, text in self.filters:
if 0 <= i < self.sourceModel().columnCount():
ix = self.sourceModel().index(sourceRow, i, sourceParent)
data = ix.data()
if text not in data:
return False
return True
class winMain(QtWidgets.QMainWindow):
cur_row = -1
row_id = -1
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("SqlTableModel Test")
self.setupUi()
self.setGeometry(300,200,700,500)
self.treeView.selectionModel().selectionChanged.connect(self.item_selection_changed_slot)
self.treeView.doubleClicked.connect(self.on_treeView_doubleClicked)
self.center()
self.show()
def closeEvent(self, event):
self.deleteLater()
def new_record(self):
self.cur_row = -1
self.row_id = -1
dlgDetail(self, self.cur_row, self.row_id)
self.updateStatus()
def update_record(self, cur_row, row_id, persId, lastName, firstName, country_id):
trace("update_record() called. row: {cur_row}, id: {row_id}")
record = modelTable.record()
row = modelTable.rowCount()
if cur_row > -1: # existing entry
trace(f"storing existing -> {lastName} (id: {row_id}) on row {cur_row}")
row = cur_row
record.setValue("id", row_id)
else:
trace(f"storing new -> {lastName} (id: {row_id}) on row {cur_row}")
row = modelTable.rowCount()
modelTable.insertRow(row)
record.setValue("persId", persId)
record.setValue("lastName", lastName)
record.setValue("firstName", firstName)
record.setValue("name", country_id)
# Update Model
modelTable.setRecord(row, record)
# Update Database
if modelTable.submitAll():
trace("success on storing data.")
else:
print("error on storing data: ", modelTable.lastError().text())
if cur_row == -1:
# get used row_id
record_display = modelTable.record(row)
row_id = record_display.value("persId")
trace(f" got new_row id from database: {row_id} after save.")
self.updateStatus()
# Remember current row data
self.cur_row = row
self.row_id = row_id
print (f"returning row: {row}, row_id: {row_id}")
return row, row_id
def edit_record(self, sourceIdx):
if not sourceIdx:
sourceIdx = self.treeView.currentIndex()
# check if multiple selected rows exist
if len(self.treeView.selectionModel().selectedRows()) > 1:
reply = QtWidgets.QMessageBox.question(self, f"Editing multiple records",
f"Do you want to edit *all* the selected records?\rYes = Edit all records, No = Edit only current record",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No | QtWidgets.QMessageBox.Cancel,
QtWidgets.QMessageBox.Yes)
if reply == QtWidgets.QMessageBox.Yes:
# load all selected rows
index_list = []
for model_index in self.treeView.selectionModel().selectedRows():
index = QtCore.QPersistentModelIndex(model_index)
index_list.append(index)
offset = 0
for index in index_list:
cur_row = index.row()
ix = self.treeView.model().index(index.row(), 0) # column which contains the id
row_id = ix.data()
dlgDetail(self, cur_row, row_id)
offset += 20
return True
# only single selection
trace("single selection")
self.cur_row = sourceIdx.row()
ix = self.treeView.model().index(sourceIdx.row(), 0) # column which contains the id
self.row_id = ix.data()
dlgDetail(self, self.cur_row, self.row_id)
self.updateStatus()
@QtCore.pyqtSlot(QtCore.QModelIndex)
def on_treeView_doubleClicked(self, index):
self.edit_record(index)
def handleFilterActivated(self):
header = self.treeView.header()
filters = []
for i in range(header.count()):
text = header.filterText(i)
if text:
filters.append((i, text))
proxy = self.treeView.model()
proxy.filters = filters
self.updateStatus()
QtCore.pyqtSlot()
def item_selection_changed_slot(self):
selected = self.treeView.selectionModel()
indexes = selected.selectedIndexes()
global g_selected_count
g_selected_count = len(selected.selectedRows())
sourceIdx = self.treeView.currentIndex()
trace(f"sourceIdx.row() -> {sourceIdx.row()}")
ix = self.treeView.model().index(sourceIdx.row(), 0) # column which contains the id
self.cur_row = sourceIdx.row()
self.row_id = ix.data()
trace(f"setting cur_row to -> {self.cur_row}")
trace(f"setting row_id to -> {self.row_id}")
record = modelTable.record(self.cur_row)
persId = record.value("persId")
lastName = record.value("lastName")
firstName = record.value("firstName")
country = record.value("name")
trace(f"self.cur_row: {self.cur_row}")
trace(f"self.row_id : {self.row_id}")
trace(f"persId: {persId}")
trace(f"lastName: {lastName}")
self.updateStatus()
def refresh(self):
cur_row = -1
row_id = -1
self.clear_all_filters()
modelTable.select() # fetch the data of the table into the model
self.treeView.sortByColumn(2, QtCore.Qt.DescendingOrder)
self.updateStatus()
self.statusBar.showMessage(f"data reloaded.")
def updateStatus(self):
global g_hits_count, g_total_count, g_selected_count
sStatusText = f"Selected: {str(g_selected_count)} / Hits: {str(g_hits_count)} / Total: {str(g_total_count)} | Current row: {self.cur_row}, row id: {self.row_id}"
self.statusBar.showMessage(sStatusText)
def keyReleaseEvent(self, eventQKeyEvent):
key = eventQKeyEvent.key()
modifiers = QtWidgets.QApplication.keyboardModifiers()
if modifiers == QtCore.Qt.ShiftModifier and key == QtCore.Qt.Key_Escape:
self.clear_all_filters()
def keyPressEvent(self, event):
key = event.key()
modifiers = QtWidgets.QApplication.keyboardModifiers()
if modifiers != QtCore.Qt.ShiftModifier:
focus_obj = self.focusWidget()
if key == QtCore.Qt.Key_Return:
if type(focus_obj) == QtWidgets.QTreeView:
self.edit_record(self.treeView.currentIndex())
elif key == QtCore.Qt.Key_Escape:
if type(focus_obj) == QtWidgets.QLineEdit:
focus_obj.clear()
def clear_all_filters(self):
# clear all inputs of type QLineEdit
lineEdits = self.findChildren(QtWidgets.QLineEdit)
for lineEdit in lineEdits:
lineEdit.clear()
def center(self):
frameGm = self.frameGeometry()
screen = QtWidgets.QApplication.desktop().screenNumber(QtWidgets.QApplication.desktop().cursor().pos())
centerPoint = QtWidgets.QApplication.desktop().screenGeometry(screen).center()
frameGm.moveCenter(centerPoint)
self.move(frameGm.topLeft())
def setupUi(self):
self.centralwidget = QtWidgets.QWidget(self)
hBox = QtWidgets.QHBoxLayout(self.centralwidget)
self.treeView = QtWidgets.QTreeView(self.centralwidget)
self.treeView.setRootIsDecorated(False)
self.treeView.setSortingEnabled(True)
self.treeView.setAlternatingRowColors(True)
self.treeView.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.treeView.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.treeView.header().setStretchLastSection(True)
hBox.addWidget(self.treeView)
self.setCentralWidget(self.centralwidget)
header = FilterHeader(self.treeView)
self.treeView.setHeader(header)
self.treeView.sortByColumn(2, QtCore.Qt.DescendingOrder)
# StatusBar
self.statusBar = QtWidgets.QStatusBar()
self.setStatusBar(self.statusBar)
# ToolBar
exitAct = QtWidgets.QAction("Exit", self, shortcut="Ctrl+Q", triggered=QtWidgets.qApp.quit)
newRecordAct = QtWidgets.QAction("New", self, shortcut="Ctrl+N", triggered=self.new_record)
editRecordAct = QtWidgets.QAction("Edit", self, shortcut="Return", triggered=self.edit_record)
refreshAct = QtWidgets.QAction("Refresh", self, shortcut="F5", triggered=self.refresh)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAct)
self.toolbar.addSeparator()
self.toolbar.addAction(newRecordAct)
self.toolbar.addAction(editRecordAct)
self.toolbar.addSeparator()
self.toolbar.addAction(refreshAct)
modelTable.setTable(MY_TABLE)
modelTable.setHeaderData(0, QtCore.Qt.Horizontal, "row id")
modelTable.setHeaderData(1, QtCore.Qt.Horizontal, "ID")
modelTable.setHeaderData(2, QtCore.Qt.Horizontal, "Last Name")
modelTable.setHeaderData(3, QtCore.Qt.Horizontal, "First Name")
modelTable.setHeaderData(4, QtCore.Qt.Horizontal, "Country")
modelTable.setRelation(4, QtSql.QSqlRelation("country", "id", "name"))
modelTable.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)
self.treeView.setModel(modelTable) # display data of the SQLTableModel into the QTreeView
if not TRACE:
self.treeView.setColumnHidden(0, True)
# enable human sorting
proxy = HumanProxyModel(self)
proxy.setSourceModel(modelTable)
self.treeView.setModel(proxy)
# enable filtering
header.setFilterBoxes(modelTable.columnCount())
header.filterActivated.connect(self.handleFilterActivated)
# update counters
global g_total_count, g_hits_count
g_total_count = modelTable.rowCount()
g_hits_count = g_total_count
self.updateStatus()
def create_sample_data():
modelQuery.setQuery("""CREATE TABLE IF NOT EXISTS country (
id INTEGER PRIMARY KEY UNIQUE NOT NULL,
name TEXT
)""")
modelQuery.setQuery("""CREATE TABLE IF NOT EXISTS person (
id INTEGER PRIMARY KEY UNIQUE NOT NULL,
persId TEXT,
lastName TEXT,
firstName TEXT,
country_id INTEGER NOT NULL DEFAULT 3,
FOREIGN KEY (country_id) REFERENCES country(id)
)""")
# create some sample data for our model
modelQuery.setQuery("INSERT INTO country (id, name) VALUES (0, 'None')")
modelQuery.setQuery("INSERT INTO country (id, name) VALUES (1, 'Angola')")
modelQuery.setQuery("INSERT INTO country (id, name) VALUES (2, 'Serbia')")
modelQuery.setQuery("INSERT INTO country (id, name) VALUES (3, 'Georgia')")
modelQuery.setQuery("INSERT INTO person (id, persId, lastName, firstName, country_id) VALUES (1, '1001', 'a', 'Robert', 1)")
modelQuery.setQuery("INSERT INTO person (id, persId, lastName, firstName, country_id) VALUES (2, '1002', 'b', 'Brad', 2)")
modelQuery.setQuery("INSERT INTO person (id, persId, lastName, firstName, country_id) VALUES (3, '1003', 'c', 'Angelina', 3)")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
create_sample_data()
window = winMain()
sys.exit(app.exec_())
最佳答案
不要使用可视行,因为当行重新排序时它可能会发生变化,相反,您应该寻找一些持久元素,一个可能的解决方案是使用 QPersintenModelIndex。
在下面的代码中我实现了该逻辑:
class dlgDetail(QtWidgets.QDialog):
def __init__(self, parent, index):
super(dlgDetail, self).__init__(parent)
self.setModal(False)
self.setWindowModality(QtCore.Qt.NonModal)
self.index = index
self.parent = self.parent()
trace(f"dlgDetail was called with cur_row: {index.row()}")
self.setupUi(self)
# connect signals
self.accepted.connect(self.dlgDetail_accepted)
self.rejected.connect(self.dlgDetail_rejected)
self.pbNew.clicked.connect(self.on_pbNew_clicked)
self.pbSave.clicked.connect(self.on_pbSave_clicked)
self.pbSave.setDefault(True)
self.pbDel.clicked.connect(self.on_pbDel_clicked)
self.pbCancel.clicked.connect(self.on_pbCancel_clicked)
if self.index.isValid():
record_display = modelTable.record(self.index.row())
persId = record_display.value("persId")
lastName = record_display.value("lastName")
firstName = record_display.value("firstName")
country = record_display.value("name")
self.efId.setText(persId)
self.efLastName.setText(lastName)
self.efFirstName.setText(firstName)
self.populate_comboBox(self.cmbCountry, country)
else:
modelQuery.setQuery("SELECT IFNULL(MAX(id),0)+1 FROM person")
self.row_id = modelQuery.data(modelQuery.index(0, 0))
self.efId.setText("new" + str(self.row_id))
self.efLastName.setText("new" + str(self.row_id))
self.efFirstName.setText("new" + str(self.row_id))
self.populate_comboBox(self.cmbCountry, 0)
self.show()
# ...
@QtCore.pyqtSlot()
def on_pbSave_clicked(self):
self.parent.update_record(
self.index,
self.efId.text(),
self.efLastName.text(),
self.efFirstName.text(),
self.cmbCountry.currentIndex()
)
# ...
class winMain(QtWidgets.QMainWindow):
# ...
def new_record(self):
dlgDetail(self, QtCore.QPersistentModelIndex())
self.updateStatus()
def update_record(self, index, persId, lastName, firstName, country_id):
if index.isValid():
row = index.row()
record = modelTable.record(row)
else:
row = modelTable.rowCount()
modelTable.insertRow(row)
record = modelTable.record()
record.setValue("persId", persId)
record.setValue("lastName", lastName)
record.setValue("firstName", firstName)
record.setValue("name", country_id)
modelTable.setRecord(row, record)
# Update Database
if modelTable.submitAll():
trace("success on storing data.")
else:
print("error on storing data: ", modelTable.lastError().text())
if not index.isValid():
record_display = modelTable.record(0)
row_id = record_display.value("persId")
trace(f" got new_row id from database: {row_id} after save.")
self.updateStatus()
def edit_record(self, sourceIdx):
if len(self.treeView.selectionModel().selectedRows()) > 1:
reply = QtWidgets.QMessageBox.question(
self,
f"Editing multiple records",
f"Do you want to edit *all* the selected records?\rYes = Edit all records, No = Edit only current recaord",
QtWidgets.QMessageBox.Yes
| QtWidgets.QMessageBox.No
| QtWidgets.QMessageBox.Cancel,
QtWidgets.QMessageBox.Yes,
)
if reply == QtWidgets.QMessageBox.Yes:
for proxy_index in self.treeView.selectionModel().selectedRows():
proxy_model = proxy_index.model()
index = proxy_model.mapToSource(proxy_index)
p_index = QtCore.QPersistentModelIndex(index)
dlgDetail(self, p_index)
return True
if not sourceIdx:
sourceIdx = self.treeView.currentIndex()
if not sourceIdx.isValid():
trace("not selection")
return False
# only single selection
trace("single selection")
proxy_model = sourceIdx.model()
index = proxy_model.mapToSource(sourceIdx)
dlgDetail(self, index)
self.updateStatus()
完整的解决方案是 here
关于python - 使用 QSqlTableModel 在 QTreeView 上存储期间处理更改的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57201204/
猫f1.txt阿曼维沙尔阿杰贾伊维杰拉胡尔曼尼什肖比特批评塔夫林现在输出应该符合上面给定的条件 最佳答案 您可以在文件读取循环中设置一个计数器并打印它, 计数=0 读取行时做 让我们数一数++ if
我正在尝试查找文件 1 和文件 2 中的共同行。如果公共(public)行存在,我想写入文件 2 中的行,否则打印文件 1 中的非公共(public)行。fin1 和 fin2 是这里的文件句柄。它读
我有这个 SQL 脚本: CREATE TABLE `table_1` ( `IDTable_1` int(11) NOT NULL, PRIMARY KEY (`IDTable_1`) );
我有 512 行要插入到数据库中。我想知道提交多个插入内容是否比提交一个大插入内容有任何优势。例如 1x 512 行插入 -- INSERT INTO mydb.mytable (id, phonen
如何从用户中选择user_id,SUB(row, row - 1),其中user_id=@userid我的表用户,id 为 1、3、4、10、11、23...(不是++) --id---------u
我曾尝试四处寻找解决此问题的最佳方法,但我找不到此类问题的任何先前示例。 我正在构建一个基于超本地化的互联网购物中心,该区域分为大约 3000 个区域。每个区域包含大约 300 个项目。它们是相似的项
preg_match('|phpVersion = (.*)\n|',$wampConfFileContents,$result); $phpVersion = str_replace('"','',
我正在尝试创建一个正则表达式,使用“搜索并替换全部”删除 200 个 txt 文件的第一行和最后 10 行 我尝试 (\s*^(\h*\S.*)){10} 删除包含的前 10 行空白,但效果不佳。 最
下面的代码从数据库中获取我需要的信息,但没有打印出所有信息。首先,我知道它从表中获取了所有正确的信息,因为我已经在 sql Developer 中尝试过查询。 public static void m
很难说出这里问的是什么。这个问题是含糊的、模糊的、不完整的、过于宽泛的或修辞性的,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开它,visit the help center 。 已关
我试图在两个表中插入记录,但出现异常。您能帮我解决这个问题吗? 首先我尝试了下面的代码。 await _testRepository.InsertAsync(test); await _xyzRepo
这个基本的 bootstrap CSS 显示 1 行 4 列: Text Text Text
如果我想从表中检索前 10 行,我将使用以下代码: SELECT * FROM Persons LIMIT 10 我想知道的是如何检索前 10 个结果之后的 10 个结果。 如果我在下面执行这段代码,
今天我开始使用 JexcelApi 并遇到了这个:当您尝试从特定位置获取元素时,不是像您通常期望的那样使用sheet.getCell(row,col),而是使用sheet.getCell(col,ro
我正在尝试在我的网站上开发一个用户个人资料系统,其中包含用户之前发布的 3 个帖子。我可以让它选择前 3 条记录,但它只会显示其中一条。我是不是因为凌晨 2 点就想编码而变得愚蠢? query($q)
我在互联网上寻找答案,但找不到任何答案。 (我可能问错了?)我有一个看起来像这样的表: 我一直在使用查询: SELECT title, date, SUM(money) FROM payments W
我有以下查询,我想从数据库中获取 100 个项目,但 host_id 多次出现在 urls 表中,我想每个 host_id 从该表中最多获取 10 个唯一行。 select * from urls j
我的数据库表中有超过 500 行具有特定日期。 查询特定日期的行。 select * from msgtable where cdate='18/07/2012' 这将返回 500 行。 如何逐行查询
我想使用 sed 从某一行开始打印 n 行、跳过 n 行、打印 n 行等,直到文本文件结束。例如在第 4 行声明,打印 5-9,跳过 10-14,打印 15-19 等 来自文件 1 2 3 4 5 6
我目前正在执行验证过程来检查用户的旧密码,但问题是我无法理解为什么我的查询返回零行,而预期它有 1 行。另一件事是,即使我不将密码文本转换为 md5,哈希密码仍然得到正确的答案,但我不知道为什么会发生
我是一名优秀的程序员,十分优秀!