猿问

如何在 Python PyQt5 QTableView 中对齐(居中)行数据?

我想对齐模型中的所有行。我在“QtDesigner”中将 .ui 编译为 .py 并创建 form.py。Ui_MainWindow 来自 form.py 。你能用例子解释解决办法吗?


回复:我想对齐模型中的所有行。我在“QtDesigner”中将 .ui 编译为 .py 并创建 form.py。Ui_MainWindow 来自 form.py 。你能用例子解释解决办法吗?


class App(Ui_MainWindow):

    def __init__(self, window):

        self.setupUi(window)

        # code...

        numbers = [["Thomas","17776661122",❌],["Parker","1777666331",❌],["Michael","17775553322",❌]]

        CreateTable()

    def CreateTable(self,fromlist):

        for i in range(0,len(fromlist)):

            self.model.addCustomer(Customer(fromlist[i][0],fromlist[i][1],fromlist[i][2]))

            ### align code

        # code...


这是我的 QtTableView 模型。


class Customer(object):

    def __init__(self,name,number,status):

        self.name = name

        self.number = number

        self.status = status


class CustomerTableModel(QtCore.QAbstractTableModel):


    ROW_BATCH_COUNT = 15


    def __init__(self):

        super(CustomerTableModel,self).__init__()

        self.headers = ['               İsim                     ','  Telefon No (Örn 9053xx..)   ','   Mesaj Durumu   ']

        self.customers  = []

        self.rowsLoaded = CustomerTableModel.ROW_BATCH_COUNT


    def rowCount(self,index=QtCore.QModelIndex()):

        if not self.customers:

            return 0


        if len(self.customers) <= self.rowsLoaded:

            return len(self.customers)

        else:

            return self.rowsLoaded


    def canFetchMore(self,index=QtCore.QModelIndex()):

        if len(self.customers) > self.rowsLoaded:

            return True

        else:

            return False


   

天涯尽头无女友
浏览 186回答 2
2回答

一只斗牛犬

我找到了解决方案。我将这一行添加到...def data(self,index,role=QtCore.Qt.DisplayRole):&nbsp; &nbsp; col = index.column()&nbsp; &nbsp; customer = self.customers[index.row()]&nbsp; &nbsp; if role == QtCore.Qt.DisplayRole:&nbsp; &nbsp; &nbsp; &nbsp; if col == 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return QtCore.QVariant(customer.name)&nbsp; &nbsp; &nbsp; &nbsp; elif col == 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return QtCore.QVariant(customer.number)&nbsp; &nbsp; &nbsp; &nbsp; elif col == 2:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return QtCore.QVariant(customer.status)&nbsp; &nbsp; &nbsp; &nbsp; return QtCore.QVariant()&nbsp; &nbsp; # ADDED LINES&nbsp; &nbsp; elif role == QtCore.Qt.TextAlignmentRole:&nbsp; &nbsp; &nbsp; &nbsp; return QtCore.Qt.AlignCenter&nbsp; &nbsp; ###

茅侃侃

没有找到在 QTableView 上创建表格的方法,但是对于每个项目设置,此代码都可以对齐;data = QTableWidget(["17776661122"])table.setItem(x,y,data).setTextAlignment(Qt.AlignHCenter)
随时随地看视频慕课网APP

相关分类

Python
我要回答