【轉載】pyqt QTableWidget的使用,實現table輸出

來源:互聯網
上載者:User

標籤:

轉載地址: http://blog.sina.com.cn/s/blog_9b78c91101019sgi.html

 

QTableWidget是QT程式中常用的顯示資料表格的空間,很類似於VC、C#中的DataGrid。

說到QTableWidget,就必須講一下它跟QTabelView的區別了。QTableWidget是QTableView的子類,主要的區別是QTableView可以使用自訂的資料模型來顯示內容(也就是先要通過setModel來綁定資料來源),而QTableWidget則只能使用標準的資料模型,並且其儲存格資料是QTableWidgetItem的對象來實現的(也就是不需要資料來源,將逐個儲存格內的資訊填好即可)。

這主要體現在QTableView類中有setModel成員函數,而到了QTableWidget類中,該成員函數變成了私人。

使用QTableWidget就離不開QTableWidgetItem。QTableWidgetItem用來表示表格中的一個儲存格,正個表格都需要用逐個儲存格構建起來。

繼承圖:

QtableWidget是繼承於QtableView的。所以QtableView的方法也在QtableWidget中繼承了。
QTableWidget類提供了一個預設模式的表格,它是基於Item的,這個Item是由QTableWidgetItem提供的。如果你要構建自己的資料模式,請使用QTableView而不是QTableWidget。

 

一個簡單的QTableWidget小程式:

 1 #!/usr/bin/env python   2 #coding=utf-8   3 from PyQt4.QtGui  import *  #目測table的類應該是在qt.gui裡面的 4 from PyQt4.QtCore import *     5 class MyDialog(QDialog):   6     def __init__(self, parent=None):   7         super(MyDialog, self).__init__(parent)   8         self.MyTable = QTableWidget(4,3)   9         self.MyTable.setHorizontalHeaderLabels([‘姓名‘,‘身高‘,‘體重‘])  10           11         newItem = QTableWidgetItem("松鼠")  12         self.MyTable.setItem(0, 0, newItem)  13           14         newItem = QTableWidgetItem("10cm")  15         self.MyTable.setItem(0, 1, newItem)  16           17         newItem = QTableWidgetItem("60g")  18         self.MyTable.setItem(0, 2, newItem)   19         20         layout = QHBoxLayout()  21         layout.addWidget(self.MyTable)  22         self.setLayout(layout)      23           24           25 if __name__ == ‘__main__‘:  26     import sys  27     app = QApplication(sys.argv)  28     myWindow = MyDialog()  29     myWindow.show()  30     sys.exit(app.exec_()) 

 

self.MyTable = QTableWidget(4,3) 構造了一個QTableWidget的對象,並且設定為4行,3列
self.MyTable.setHorizontalHeaderLabels([‘姓名‘,‘身高‘,‘體重‘]) 則設定表格的表頭
newItem = QTableWidgetItem("松鼠") 則是產生了一個QTableWidgetItem的對象,並讓其名為“松鼠”
self.MyTable.setItem(0, 0, newItem) 將剛才產生的Item載入到第0行、0列處

運行結果如下:

第一部分:對QTableWidget本身的效果實現1.將表格變為禁止編輯

在預設情況下,表格裡的字元是可以更改的,比如雙擊一個儲存格,就可以修改原來的內容,如果想禁止使用者的這種操作,讓這個表格對使用者唯讀,可以這樣:

self.MyTable.setEditTriggers(QAbstractItemView.NoEditTriggers)   #MyTable是上面代碼中產生的QTableWidget對象

QAbstractItemView.NoEditTriggers是QAbstractItemView.EditTrigger枚舉中的一個,都是觸發修改儲存格內容的條件:

QAbstractItemView.NoEditTriggers 0 No editing possible. 不能對錶格內容進行修改
QAbstractItemView.CurrentChanged 1 Editing start whenever current item changes.任何時候都能對儲存格修改
QAbstractItemView.DoubleClicked 2 Editing starts when an item is double clicked.雙擊儲存格
QAbstractItemView.SelectedClicked 4 Editing starts when clicking on an already selected item.單擊已選中的內容
QAbstractItemView.EditKeyPressed 8 Editing starts when the platform edit key has been pressed over an item.
QAbstractItemView.AnyKeyPressed 16 Editing starts when any key is pressed over an item.按下任意鍵就能修改
QAbstractItemView.AllEditTriggers 31 Editing starts for all above actions.以上條件全包括
2.設定表格為整行選擇
self.MyTable.setSelectionBehavior(QAbstractItemView.SelectRows)  #整行選中的方式

QAbstractItemView.SelectionBehavior枚舉還有如下類型:

Constant Value Description
QAbstractItemView.SelectItems 0 Selecting single items.選中單個儲存格
QAbstractItemView.SelectRows 1 Selecting only rows.選中一行
QAbstractItemView.SelectColumns 2 Selecting only columns.選中一列
3.單個選中和多個選中的設定:
self.MyTable.setSelectionMode(QAbstractItemView.ExtendedSelection)  #設定為可以選中多個目標

該函數的參數還可以是:

QAbstractItemView.NoSelection      不能選擇

QAbstractItemView.SingleSelection  選中單個目標

QAbstractItemView.MultiSelection    選中多個目標

QAbstractItemView.ExtendedSelection   QAbstractItemView.ContiguousSelection 的區別不明顯,主要功能是正常情況下是單選,但按下Ctrl或Shift鍵後,可以多選

4.表格表頭的顯示與隱藏

對於水平或垂直方法的表頭,可以用以下方式進行 隱藏/顯示 的設定:

self.MyTable.verticalHeader().setVisible(False)self.MyTable.horizontalHeader().setVisible(False)

就將所有的表頭都隱藏起來了,效果如下:

5.對錶頭文字的字型、顏色進行設定

textFont = QFont( "song" ,  12 , QFont.Bold)
for x in range(self.MyTable.columnCount()): headItem = self.MyTable.horizontalHeaderItem(x) #獲得水平方向表頭的Item對象 headItem.setFont(textFont) #設定字型 headItem.setBackgroundColor(QColor(0,60,10)) #設定儲存格背景顏色 ######################經測試,該setBackgroundColor 方法無效!!!
 headItem.setTextColor(QColor(200,111,30)) #設定文字顏色

6.在儲存格裡加入控制項:

QTableWidget不僅允許把文字加到儲存格,還允許把控制項也放到儲存格中。比如,把一個下拉框加入儲存格,可以這麼做:

        self.MyCombo = QComboBox()        self.MyCombo.addItem("√")        self.MyCombo.addItem("×")                 self.MyTable.setCellWidget(1,0,self.MyCombo)   #注意行列是從0開始計數的

先產生一個QComboBox的對象, 再用QTableWidget類中的setCellWidget函數,將其填入指定的儲存格中

 

第二部分:對儲存格的進行設定1.儲存格設定字型顏色和背景顏色
newItem = QTableWidgetItem("松鼠")  newItem.setBackgroundColor(QColor(0,60,10))  newItem.setTextColor(QColor(200,111,100))          self.MyTable.setItem(0, 0, newItem) 

 

通過QTableWidgetItem類的setBackgroundColor、setTextColor函數來實現

2.設定儲存格中的字型和字元大小
textFont = QFont("song", 12, QFont.Bold)            newItem = QTableWidgetItem("松鼠")  #newItem.setBackgroundColor(QColor(0,60,10))  #newItem.setTextColor(QColor(200,111,100))   newItem.setFont(textFont)  self.MyTable.setItem(0, 0, newItem) 

首先,先產生一個字型QFont對象,並將其字型設為宋體,大小設為12,並且加粗
再利用儲存格的QTableWidgetItem類中的setFont載入給特定的儲存格。如果需要對所有的儲存格都使用這種字型,則可以使用

self.MyTable.setFont(testFont) #利用QTableWidget類中的setFont成員函數,將所有的儲存格都設成該字型

3.設定儲存格內文字的對齊:

這個比較簡單,使用newItem.setTextAlignment()函數即可,該函數的參數為儲存格內的對齊,和字元輸入順序是自左相右還是自右向左。

水平對齊有:

Constant Value Description
Qt.AlignLeft 0x0001 Aligns with the left edge.
Qt.AlignRight 0x0002 Aligns with the right edge.
Qt.AlignHCenter 0x0004 Centers horizontally in the available space.
Qt.AlignJustify 0x0008 Justifies the text in the available space.

垂直對齊:

Constant Value Description
Qt.AlignTop 0x0020 Aligns with the top.
Qt.AlignBottom 0x0040 Aligns with the bottom.
Qt.AlignVCenter 0x0080 Centers vertically in the available space.

如果兩種都要設定,只要用 Qt.AlignHCenter |  Qt.AlignVCenter 的方式即可

4.合併儲存格效果的實現:
self.MyTable.setSpan(0, 0, 3, 1)  # 其參數為: 要改變儲存格的   1行數  2列數     要合并的  3行數  4列數

5.設定儲存格的大小

首先,可以指定某個行或者列的大小

self.MyTable.setColumnWidth(2,50)  #將第2列的儲存格,設定成50寬度self.MyTable.setRowHeight(2,60)      #將第2行的儲存格,設定成60的高度

還可以將行和列的大小設為與內容相匹配

self.MyTable.resizeColumnsToContents()   #將列調整到跟內容大小相匹配self.MyTable.resizeRowsToContents()      #將行大小調整到跟內容的大學相匹配
6.獲得單擊儲存格的內容

通過實現 itemClicked (QTableWidgetItem *) 訊號的槽函數,就可以獲得按一下滑鼠到的儲存格指標,進而獲得其中的文字資訊

self.connect(self.MyTable, SIGNAL("itemClicked (QTableWidgetItem*)"), self.outSelect)  #將itemClicked訊號與函數outSelect綁定

然後實現一個outSelect函數,如下:

def outSelect(self, Item=None):        if Item==None:            return                print(Item.text())

運行程式後,單擊一個儲存格,即可獲得其中的字元了

 

【轉載】pyqt QTableWidget的使用,實現table輸出

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.