【问题标题】:QTableWidget or QTableView for toggling cell imagesQTableWidget 或 QTableView 用于切换单元格图像
【发布时间】:2019-01-11 08:48:34
【问题描述】:

我在这里寻找指导。我想要一个包含数据行的表。其中一列是空的,专用于用户输入。如果用户喜欢该行中的数据,单击空单元格将显示图像,即心脏。如果用户稍后改变主意,单击图像将删除它。 我不确定 QTableView 是否会支持它的功能。 如果我对可以使用 QTableView 或 QTableWidget 完成的假设有误,我感谢任何正确方向的指导。

提前致谢。

【问题讨论】:

    标签: python pyqt pyqt5 qtableview qtablewidget


    【解决方案1】:

    试试看:

    import sys
    from PyQt5.QtGui     import *
    from PyQt5.QtCore    import *
    from PyQt5.QtWidgets import *
    
    class MainWindow(QMainWindow):
        def __init__(self):
            QMainWindow.__init__(self)
            self.setGeometry(600, 200, 330, 180)
    
            self.tableWidget = QTableWidget()
            self.tableWidget.setRowCount(3)
            self.tableWidget.setColumnCount(3)
            self.tableWidget.setHorizontalHeaderLabels(['Product', 'Description', 'Likes/UnLikes'])
            self.setCentralWidget(self.tableWidget)
    
            for x in range(3):
                self.button = QPushButton('Likes/UnLikes', self) 
                self.button.setFlat(True)
                self.tableWidget.setItem(x, 0, QTableWidgetItem('Product{}'.format(x)))
                self.tableWidget.setItem(x, 1, QTableWidgetItem('Description'))
                self.tableWidget.setCellWidget(x, 2, self.button)
    
                self.button.clicked.connect(
                    lambda state, w=self.tableWidget.cellWidget(x,2), r=x, c=2: self.button_pushed(w, r, c)
                )
    
        def button_pushed(self, w, r, c): 
            if w.text() != "Likes/UnLikes":
                w.setIcon(QIcon(""))
                w.setText("Likes/UnLikes")
            else:
                w.setIcon(QIcon("E:/_Qt/img/heart.png"))
                w.setText(" Likes")
    
            w.setIconSize(QSize(20, 20))
            self.tableWidget.setCellWidget(r, c, w)
    
    app = QApplication(sys.argv)
    w   = MainWindow()
    w.show()
    sys.exit(app.exec_())
    

    【讨论】:

    • 谢谢。那可行。我没想过要使用按钮。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多