我正在尝试使用 PyQt5 按下时更改按钮文本。我有一个已填充的表格,每行都有一个按钮。最初,该按钮应显示“播放”,按下后应显示“暂停”。
我使用以下方法填充表格并处理按钮按下操作:
def populate_table(self, total, my_songs):
self.create_rows(total)
btn_press = 0
for row in range(total):
for col in range(4):
self.tableWidget.setItem(row, 0, QtWidgets.QTableWidgetItem(str(my_songs[row].get_title())
.strip('"\'')))
self.tableWidget.setItem(row, 1, QtWidgets.QTableWidgetItem(str(my_songs[row].get_artist())
.strip('"\'')))
self.tableWidget.setItem(row, 2, QtWidgets.QTableWidgetItem(str(my_songs[row].get_album())
.strip('"\'')))
self.tableWidget.setItem(row, 3, QtWidgets.QTableWidgetItem(str(my_songs[row].get_length())
.strip('"\'')))
# self.tableWidget.setItem(row, 4, QtWidgets.QPushButton('Play'))
self.btn_play = QPushButton("Play", self)
self.btn_play.clicked.connect(lambda: self.handle_play_button(self.btn_press))
self.tableWidget.setCellWidget(row, 4, self.btn_play)
def handle_play_button(self, btn_press):
button = QtWidgets.qApp.focusWidget()
# or button = self.sender()
index = self.tableWidget.indexAt(button.pos())
if index.isValid():
self.btn_press += 1
print(index.row(), index.column(), btn_press)
self.btn_play.setText("Pause") #This does not work
这让我知道按下了哪个按钮,以便我可以继续播放歌曲。下面的例子给出here https://www.tutorialspoint.com/pyqt/pyqt_qpushbutton_widget.htm我尝试使用setText
,但我没有看到任何可见的文本变化。关于如何做到这一点有什么建议吗?谢谢!
EDIT:
代表我的错误。无论按下哪个按钮,最后创建的按钮都会更改为“暂停”。我可以用吗index.row()
以某种方式索引按钮按下进行切换?