我正在创建一个具有搜索选项的工具。搜索后,我正在创建一个数据框并将其显示在 QTableView 中。1-我需要在表格视图中的每一行显示一个单选按钮。单选按钮将是表格视图中的第一列。我找到了表格视图方法setIndexWidget()
,但不知道如何实现它。
2-一旦我在第一行选择单选按钮并单击显示数据按钮,我在 tableview MemberNumber,FirstName,LastName 中有 3 列,它应该在 msg 框中显示成员编号。
下面是我写到现在的代码——
import sys
import pandas as pd
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import QAbstractTableModel, Qt
from PyQt5.QtWidgets import (QWidget, QLabel, QPushButton, QGridLayout, QDesktopWidget,
QApplication, QTableView,QGroupBox,QLineEdit,QRadioButton,QModelIndex)
class Radio_button(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# set window title
self.setWindowTitle('Search Window')
self.show()
# self.setFixedSize(650, 450)
window_layout = QGridLayout()
rect = QtCore.QRect(10, 10, 300, 200)
window_layout.setGeometry(rect)
self.setLayout(window_layout)
# Radio button for male
self.radioButton_male = QRadioButton('R1')
self.table=QTableView()
window_layout.addWidget(self.table)
# adding signal and slot
self.radioButton_male.toggled.connect(lambda: self.maleselected('Male'))
# Radio button for female
self.radioButton_female = QRadioButton('R2')
# adding signal and slot
self.radioButton_female.toggled.connect(lambda: self.maleselected('Female'))
# Add label
self.label = QLabel()
# Add button
self.show_data=QPushButton('Show Data',clicked = lambda : self.showData())
window_layout.addWidget(self.label,3,0)
window_layout.addWidget(self.radioButton_male,1,0)
window_layout.addWidget(self.radioButton_female,2,0)
window_layout.addWidget(self.table,0,0)
window_layout.addWidget(self.show_data,4,0)
self.radioButton=QRadioButton()
self.index=0
self.table.setIndexWidget(QModelIndex,self.radioButton)
def maleselected(self, gender):
self.label.setText("You are "+gender)
def createdf(self):
data = {'Name':['Tom', 'nick', 'krish', 'jack'],
'Age':[20, 21, 19, 18]}
df=pd.DataFrame(data)
return df
def showData(self):
model = pandasModel(self.createdf())
self.table.setModel(model)
class pandasModel(QAbstractTableModel):
def __init__(self, data):
QAbstractTableModel.__init__(self)
self._data = data
def rowCount(self, parent=None):
return self._data.shape[0]
def columnCount(self, parnet=None):
return self._data.shape[1]
def data(self, index, role=Qt.DisplayRole):
if index.isValid():
if role == Qt.DisplayRole:
return str(self._data.iloc[index.row(), index.column()])
return None
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[col]
return None
def main():
app = QApplication(sys.argv)
mc = Radio_button()
sys.exit(app.exec_())
if __name__ == '__main__':
main()