第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何為 QTableView 列設(shè)置標(biāo)題標(biāo)簽?

如何為 QTableView 列設(shè)置標(biāo)題標(biāo)簽?

UYOU 2023-10-26 15:31:06
我正在使用 PyQt5 開(kāi)發(fā)一個(gè) Python GUI 應(yīng)用程序,它有一個(gè)用于顯示數(shù)據(jù)的 QTableView。這是代碼:import sysfrom PyQt5 import QtWidgets, QtCorefrom PyQt5.QtCore import Qtclass DataModel(QtCore.QAbstractTableModel):    def __init__(self):        super().__init__()        self.data = []    def data(self, index, role):        if role == Qt.DisplayRole:            return self.data[index.row()][index.column()]    def rowCount(self, index):        return len(self.data)    def columnCount(self, index):        return len(self.data[0])class MainWindow(UI.UserInterface):    def __init__(self):        super().__init__()        self.model = DataModel()        self.load()        self.TableView.setModel(self.model)        self.TableView.resizeColumnsToContents()        self.TableView.horizontalHeader().setStretchLastSection(True)    def load(self):        try:            self.model.data = [(1, '2020-01-10 00:00:00', 'KANIA', 'HENRYK', 4219)]        except Exception:            passif __name__ == "__main__":    app = QtWidgets.QApplication(sys.argv)    window = MainWindow()    window.show()    app.exec_()該類(lèi)UI.UserInterface位于單獨(dú)的模塊中。它具有QWidgets的界面和布局QWidgets。其中之一是QTableView。我似乎找不到一種方法來(lái)設(shè)置QTableView.我尋找了不同的解決方案(其中一些如下),但沒(méi)有一個(gè)有效:https://doc.qt.io/qt-5/sql-presenting.html(這個(gè)是C++寫(xiě)的,不太懂)
查看完整描述

3 回答

?
冉冉說(shuō)

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個(gè)贊

您必須實(shí)施headerData()


class DataModel(QtCore.QAbstractTableModel):

? ? # ...

? ? def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):

? ? ? ? if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:

? ? ? ? ? ? return 'Column {}'.format(section + 1)

? ? ? ? return super().headerData(section, orientation, role)

顯然,即使使用包含要顯示的標(biāo)簽的簡(jiǎn)單列表,您也可以設(shè)置自己的標(biāo)簽。


請(qǐng)注意,為子類(lèi)命名新屬性時(shí)應(yīng)非常小心,因?yàn)樗鼈兛赡芤呀?jīng)存在。

最重要的是,您不應(yīng)該覆蓋self.data.


查看完整回答
反對(duì) 回復(fù) 2023-10-26
?
青春有我

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊

這是一個(gè)使用 QtableView 和一組 headerdata 的示例,您將能夠修改 tableview 中的數(shù)據(jù)


def exemple_table(self):

? ? ? ? database = QSqlDatabase("QPSQL")

? ? ? ? database.setHostName("localhost")

? ? ? ? database.setDatabaseName("database")

? ? ? ? database.setUserName("postgres")

? ? ? ? database.setPassword("password")

? ? ? ? database.open()

? ? ? ??

? ? ? ? model_ft = QSqlTableModel(db=database)

? ? ? ? model_ft.setTable('table')

? ? ? ??

? ? ? ? model_ft.setHeaderData(0, Qt.Horizontal,"id")

? ? ? ? model_ft.setHeaderData(1, Qt.Horizontal,"exemple01")

? ? ? ? model_ft.setHeaderData(2, Qt.Horizontal,"exemple02")

? ? ? ? model_ft.setHeaderData(3, Qt.Horizontal,"exemple03")

? ? ? ? model_ft.setHeaderData(4, Qt.Horizontal,"exemple04")

? ? ? ? model_ft.setHeaderData(5, Qt.Horizontal,"exemple05")

? ? ? ? model_ft.setHeaderData(6, Qt.Horizontal,"exemple06")

? ? ? ? model_ft.setHeaderData(7, Qt.Horizontal,"exemple07")

? ? ? ??

? ? ? ? model_ft.removeColumns(8,1)

? ? ? ? date = str(datetime.date.today())

? ? ? ??

? ? ? ? self.tableView.setModel(model_ft)

? ? ? ? self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

? ? ? ??

? ? ? ? model_ft.setSort(0, Qt.DescendingOrder)

? ? ? ? model_ft.select()

? ? ? ? filter_ft = "date_d ='%s' " % (date_1)

? ? ? ? model_ft.setFilter(filter_ft)



查看完整回答
反對(duì) 回復(fù) 2023-10-26
?
HUH函數(shù)

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊

設(shè)置列和行名稱(chēng)的覆蓋headerData方法QTableAbstractModel


def headerData(self, section: int, orientation: PySide6.QtCore.Qt.Orientation, role: int = ...):

    #for setting columns name

    if orientation == Qt.Horizontal and role == Qt.DisplayRole:

        return f"Column {section + 1}"

    #for setting rows name

    if orientation == Qt.Vertical and role == Qt.DisplayRole:

        return f"Row {section + 1}"

工作代碼:

import sys

import requests


import PySide6

from PySide6.QtWidgets import QTableView, QWidget, QApplication, QGridLayout, QHeaderView

from PySide6.QtCore import Qt, QAbstractTableModel

from PySide6.QtGui import QColor, QIcon, QPixmap


from datetime import datetime



class MagicIcon():

    def __init__(self, link):

        self.link = link

        self.icon = QIcon()

        try:

            response = requests.get(self.link)

            pixmap = QPixmap()

            pixmap.loadFromData(response.content)

            self.icon = QIcon(pixmap)

        except:

            pass



class TableModel(QAbstractTableModel):


    def headerData(self, section: int, orientation: PySide6.QtCore.Qt.Orientation, role: int = ...):

        if orientation == Qt.Horizontal and role == Qt.DisplayRole:

            # return f"Column {section + 1}"

            return self.columns[section]

        if orientation == Qt.Vertical and role == Qt.DisplayRole:

            return f"{section + 1}"


    def __init__(self, _data):

        self.columns = ["Account", "Investment", "KYC", "Investment Date"]

        # super().__init__(self)

        super(TableModel, self).__init__()

        self._data = _data

        self.calendarLink = "https://img.icons8.com/fluency/48/000000/windows-calendar.png"

        self.dollarLink = "https://img.icons8.com/external-vitaliy-gorbachev-lineal-color-vitaly-gorbachev/40/000000/external-dollar-currency-vitaliy-gorbachev-lineal-color-vitaly-gorbachev-1.png"

        self.analysis = "https://img.icons8.com/external-flatarticons-blue-flatarticons/65/000000/external-analysis-digital-marketing-flatarticons-blue-flatarticons-1.png"

        self.bug = "https://img.icons8.com/offices/30/000000/bug.png"

        self.account = "https://img.icons8.com/plumpy/24/000000/edit-administrator.png"

        self.approvedLink = "https://img.icons8.com/external-bearicons-flat-bearicons/40/000000/external-approved-approved-and-rejected-bearicons-flat-bearicons-9.png"

        self.rejectedLink = "https://img.icons8.com/external-bearicons-flat-bearicons/40/000000/external-rejected-approved-and-rejected-bearicons-flat-bearicons-11.png"

        self.naLink = "https://img.icons8.com/color/48/000000/not-applicable.png"


        self.calendarIcon = MagicIcon(self.calendarLink).icon

        self.accountIcon = MagicIcon(self.account).icon

        self.dollarIcon = MagicIcon(self.dollarLink).icon

        self.approvedIcon = MagicIcon(self.approvedLink).icon

        self.rejectedIcon = MagicIcon(self.rejectedLink).icon

        self.naIcon = MagicIcon(self.naLink).icon


    def data(self, index, role):

        if role == Qt.DisplayRole:

            value = self._data[index.row()][index.column()]

            if isinstance(value, datetime):

                return value.strftime("%Y-%m-%d")

            if isinstance(value, float):

                return f"{value:.2f}"

            return value

        if role == Qt.TextAlignmentRole:

            return Qt.AlignHCenter + Qt.AlignVCenter


        if role == Qt.BackgroundRole:

            return QColor("#adcdff") if index.row() % 2 == 0 else QColor("#d8ffc2")


        if role == Qt.DecorationRole:

            value = self._data[index.row()][index.column()]

            

            if value is None:

                return self.naIcon

            if isinstance(value, datetime):

                return self.calendarIcon

            if index.column() == 0:

                return self.accountIcon

            if index.column() == 1:

                return self.dollarIcon

            if index.column() == 2:

                if value == True:

                    return self.approvedIcon

                elif value == False:

                    return self.rejectedIcon

                return self.naIcon


    def rowCount(self, index):

        return len(self._data)


    def columnCount(self, index):

        return len(self._data[0])



class MainWindow(QWidget):

    def __init__(self):

        # super().__init__()

        super(MainWindow, self).__init__()

        self.resizeEvent = self.onResize

        self.table = QTableView()

        

        self.setWindowIcon(MagicIcon(

            "https://img.icons8.com/external-flatarticons-blue-flatarticons/65/000000/external-analysis-digital-marketing-flatarticons-blue-flatarticons-1.png"

        ).icon)


        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # self.table.setSizeAdjustPolicy(QHeaderView.AdjustIgnored)

        # self.table.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)

        data = [

            ["Andrew Mike", 15.255, True, datetime(2022, 1, 5)],

            ["Eliza Petterson", 353.555, False, datetime(2020, 1, 5)],

            ["Joseph Samuel", 123, None, datetime(2020, 1, 15)],

            ["Nita Singh", 266, True, datetime(2022, 2, 7)],

            ["Rahul Chakrabarti", 102, True, datetime(2019, 10, 15)],

        ]

        self.model = TableModel(data)

        self.table.setModel(self.model)

        self.header = self.table.horizontalHeader()

        # self.header.setSectionResizeMode(0, QHeaderView.Stretch)

        # self.header.setSectionResizeMode(1, QHeaderView.)

        # self.header.setSectionResizeMode(2, QHeaderView.ResizeToContents)

        self.layout = QGridLayout()

        self.layout.addWidget(self.table, 0, 0)

        self.setLayout(self.layout)


    def onResize(self, event):

        # print('old', event.oldSize(), 'new', event.size())

        # super(MainWindow, self).resizeEvent(event)

        pass



if __name__ == "__main__":

    app = QApplication(sys.argv)

    wid = MainWindow()

    wid.show()

    sys.exit(app.exec())

https://img1.sycdn.imooc.com/653a15fa000125f313650767.jpg

查看完整回答
反對(duì) 回復(fù) 2023-10-26
  • 3 回答
  • 0 關(guān)注
  • 399 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)