PyQt5の高度なインターフェイス制御のQTableWidget(4)



Qtablewidget Pyqt5 Advanced Interface Control



序文

QTableWidgetは、Qtプログラムでデータテーブルを表示するために一般的に使用されるコントロールです。C#のDataGridに似ています。 QTableWidgetは、標準データモデルを使用するQTableViewのサブクラスです。そして、そのユニットデータはQTableWidgetItemオブジェクトによって実装されます。QTableWidgetを使用する場合は、QTableWidgetItemが必要です。テーブル内のセルを表すために使用され、テーブル全体が個々のセルで構成されます

QTableWidgetクラスの一般的なメソッド

方法 説明
setROwCount(int row) QTableWidgetテーブルコントロールの行数を設定します
setColumnCount(int col) QTableWidgetテーブルコントロールの列数を設定します
setHorizo​​ntalHeaderLabels() QTableWidgetテーブルコントロールの水平ラベルを設定します
setVerticalHeaderLabels() QTableWidgetテーブルコントロールの垂直ラベルを設定します
setItem(int、int、QTableWidgetItem) QTableWidgetテーブルコントロールの各オプションのセルコントロール内にコントロールを追加します
水平ヘッダー() QTableWidgetテーブルコントロールのテーブルヘッダーを取得して、非表示を実行します
rowCount() QTableWidgetテーブルコントロールの行数を取得します
columnCount() QTableWidgetテーブルコントロールの列数を取得します
setEditTriggers(EditTriggersトリガー) テーブルを編集できるかどうかを設定し、テーブルの列挙値を設定します
setSelectionBehavior テーブルの選択動作を設定します
setTextAlignment() セル内のテキストの配置を設定する
setSpan(int row、int column、int rowSpanCount、int columnSpanCount) セルをマージして、セルの行行、列列を変更し、rowSpancount行番号とcolumnSpanCount列番号をマージします
行:変更する行の数
列:変更する列の数
rowSpanCount:マージする行数
columnSpanCount:マージする列の数
setShowGrid() デフォルトでは、テーブルの表示はグリッド化されています。表示にはTrueまたはFalseを設定でき、デフォルトはTrueです。
setColumnWidth(int column、int width) セル行の幅を設定します
setRowHeight(int row、int height) セル列の高さを設定します

ルールの列挙値タイプを編集します

オプション 説明
QAbstractItemView.NoEditTriggers0No 0 フォームの内容を変更することはできません
QAbstractItemView.CurrentChanged1Editing 1 いつでもセルを変更できます
QAbstractItemView.DoubleClicked2Editing セルをダブルクリックします
QAbstractItemView.SelectedClicked4Editing 4 選択したコンテンツをクリックします
QAbstractItemView.EditKeyPressed8Editing 8 修飾キーが押されたときにセルを修飾する
QAbstractItemView.AnyKeyPressed16Editing 16 セルを変更するには、任意のキーを押します
QAbstractItemView.AllEditTriggers31Editing 31 上記のすべての条件を含む

テーブル選択動作の列挙値

選択する 説明
QAbstractItemView.SelectItems0Selecting 0 単一のセルを選択します
QAbstractItemView.SelectRows1Selecting 1 行を選択します
QAbstractItemView.SelectColumns2Selecting 列を選択します

セルテキストの水平方向の配置

オプション 説明
Qt.AlignLeft セルの内容をセルの左端に沿って揃えます
Qt.AlignRight セルの内容をセルの右端に沿って配置します
Qt.AlignHCenter 空きスペースでは、中央が横方向に表示されます
Qt.AlignJustify テキストを空き領域に揃えます。デフォルトは左から右です。

セルテキストの垂直方向の配置

オプション 説明
Qt.AlignTop 上に揃える
Qt.AlignBottom 下に揃える
Qt.AlignVCenter 利用可能なスペースで、垂直方向を中心に
Qt.AlignBaseline ベースラインに合わせる

表スペースの上下など、左右を中心に水平および垂直方向の配置を設定する場合は、Qt、AlignHCenterおよびQt、AlignVCenterを使用します。



例:QTableWidgetの基本的な使用法

import sys from PyQt5.QtWidgets import * class Table(QWidget): def __init__(self): super(Table, self).__init__() self.initUI() def initUI(self): self.setWindowTitle('QTableWidget example') self.resize(400,300) layout=QHBoxLayout() The effect of #implement is the same, four rows and three columns, so you need to use the function flexibly. Here is just a demonstration of how to set the row and column separately. TableWidget=QTableWidget(4,3) # TableWidget = QTableWidget() # TableWidget.setRowCount(4) # TableWidget.setColumnCount(3) #Set the header label in the horizontal direction and the header label in the vertical direction. Note that it must be performed after initializing the row and column. Otherwise, there is no effect. TableWidget.setHorizontalHeaderLabels(['name', 'gender', 'weight (kg)']) #Todo Optimization 1 Set the heading label in the vertical direction #TableWidget.setVerticalHeaderLabels(['1', 'Line 2', 'Line 3', 'Line 4']) #TODO Optimization 2 Set the horizontal direction table to adaptive scaling mode ##TableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) #TODO Optimization 3 Changing the table to prohibit editing #TableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) #TODO Optimization 4 Set the table to select the entire row #TableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) #TODO Optimization 5 Set the height of the row and column to match the width of the displayed content. #QTableWidget.resizeColumnsToContents(TableWidget) #QTableWidget.resizeRowsToContents(TableWidget) #TODO Optimization 6 Display and hide of table headers #TableWidget.verticalHeader().setVisible(False) #TableWidget.horizontalHeader().setVisible(False) #TOdo Optimization 7 Place controls inside a cell # comBox=QComboBox() # comBox.addItems(['男', 'female']) # comBox.addItem('unknown') # comBox.setStyleSheet('QComboBox{margin:3px}') # TableWidget.setCellWidget(0,1,comBox) # # searchBtn=QPushButton('Modify') # searchBtn.setDown(True) # searchBtn.setStyleSheet('QPushButton{margin:3px}') # TableWidget.setCellWidget(0,2,searchBtn) #adding data newItem=QTableWidgetItem('张三') TableWidget.setItem(0,0,newItem) newItem=QTableWidgetItem('male') TableWidget.setItem(0,1,newItem) newItem=QTableWidgetItem('160') TableWidget.setItem(0,2,newItem) layout.addWidget(TableWidget) self.setLayout(layout) if __name__ == '__main__': app=QApplication(sys.argv) win=Table() win.show() sys.exit(app.exec_())

最初の実行中のプログラム、表示効果は次のとおりです
ここに写真の説明を書いてください

コード分​​析

QTableWidgetオブジェクトを作成し、テーブルを4行3列に設定します



TableWidget=QTableWidget(4,3)

テーブルヘッダーを設定します

TableWidget.setHorizontalHeaderLabels(['name', 'gender', 'weight (kg)'])

QTableWidgetItemオブジェクトを生成し、それをテーブルの0行0列に追加します

newItem=QTableWidgetItem('张三') TableWidget.setItem(0,0,newItem)

最適化1: 垂直方向のテーブルヘッダーラベルを設定します



TableWidget.setVerticalHeaderLabels(['1', 'Line 2', 'Line 3', 'Line 4'])

効果は以下の通りです
ここに写真の説明を書いてください
最適化2 :テーブルヘッダーをフレックスモードに設定します
QTableWidgetオブジェクトのhorizo​​ntalHeader()関数を使用して、テーブルをアダプティブスケーリングモードに設定します。これにより、ウィンドウのサイズに応じてグリッドのサイズを変更できます。

TableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

ここに写真の説明を書いてください
最適化3 :編集を禁止するようにテーブルを設定します
デフォルトでは、テーブル内の文字を変更できます。たとえば、セルをダブルクリックすると、元のコンテンツを変更できます。この操作を無効にする場合は、ユーザー専用のテーブルを作成してください。読んで、あなたはコードを編集することができます

TableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)

ここに写真の説明を書いてください
最適化4 :テーブルが選択されています
テーブルはデフォルトで単一のセルを選択します。次のコードで、行全体を選択するように設定できます。

TableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)

ここに写真の説明を書いてください
最適化5: 行と列の幅の高さをテキストコンテンツの幅と高さに一致させます

QTableWidget.resizeColumnsToContents(TableWidget) QTableWidget.resizeRowsToContents(TableWidget)

ここに写真の説明を書いてください
最適化6:テーブルヘッダーの表示と非表示

TableWidget.verticalHeader().setVisible(False) TableWidget.horizontalHeader().setVisible(False)

ここに写真の説明を書いてください
最適化7 :セル内にコントロールを配置する
QTableWidgetを使用すると、テキストをセルに配置できるだけでなく、コントロールを配置することもできます。 PyQtの基本的なコントロールは、QTableWidget.setItem()を介して追加されます。
ここでは、ドロップダウンリストボックスとボタンがセルに追加され、コントロールとセルのマージンが3pxピクセルなどに設定され、コードは次のようになります。

comBox=QComboBox() comBox.addItems(['Men', 'female']) comBox.addItem('unknown') comBox.setStyleSheet('QComboBox{margin:3px}') TableWidget.setCellWidget(0,1,comBox) searchBtn=QPushButton('modified') searchBtn.setDown(True) searchBtn.setStyleSheet('QPushButton{margin:3px}') TableWidget.setCellWidget(0,2,searchBtn)

ここに写真の説明を書いてください

例2:テーブル内の指定された行にすばやく移動する

import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * class Table(QWidget): def __init__(self): super(Table, self).__init__() self.initUI() def initUI(self): #Set title and initial size self.setWindowTitle('QTableWidget example') self.resize(600,800) ##Horizontal layout layout=QHBoxLayout() #Instance table view (30*4) tablewidget=QTableWidget(30,4) layout.addWidget(tablewidget) for i in range(30): for j in range(4): itemContent='(%d,%d)'%(i,j) #Add data to each table tablewidget.setItem(i,j,QTableWidgetItem(itemContent)) self.setLayout(layout) #遍历表 to find the corresponding item text='(10,1)' items=tablewidget.findItems(text,Qt.MatchExactly) item=items[0] #Select cell item.setSelected(True) #Set the cell's back color to red item.setForeground(QBrush(QColor(255,0,0))) row=item.row() #Locate by mouse wheel to quickly locate the eleventh line tablewidget.verticalScrollBar().setSliderPosition(row) if __name__ == '__main__': app=QApplication(sys.argv) table=Table() table.show() sys.exit(app.exec_())

効果は以下のとおりです
ここに写真の説明を書いてください

例3:QTableWidgetの高度な使用法

import sys from PyQt5.QtWidgets import (QWidget, QTableWidget, QHBoxLayout, QApplication, QTableWidgetItem) from PyQt5.QtGui import QBrush, QColor, QFont from PyQt5.QtCore import Qt class Table(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): #Set title and initial size self.setWindowTitle('QTableWidget example') self.resize(430, 230) #Horizontal layout, the initial form is (4*3), added to the layout conLayout = QHBoxLayout() tableWidget = QTableWidget(5,3) conLayout.addWidget(tableWidget) #设置水平头标签 tableWidget.setHorizontalHeaderLabels(['name', 'gender', 'weight(kg)']) #Create a new entry, set the background color, add to the specified row of the table newItem = QTableWidgetItem('张三') #newItem.setForeground(QBrush(QColor(255, 0, 0))) tableWidget.setItem(0, 0, newItem) # Create a new entry, set the background color, add to the specified row of the table newItem = QTableWidgetItem('male') #newItem.setForeground(QBrush(QColor(255, 0, 0))) tableWidget.setItem(0, 1, newItem) # Create a new entry, set the background color, add to the specified row of the table newItem = QTableWidgetItem('160') #newItem.setForeground(QBrush(QColor(255, 0, 0))) tableWidget.setItem(0, 2, newItem) # newItem = QTableWidgetItem('李四') ##Add font bold, black font # newItem.setFont(QFont('Times',12,QFont.Black)) # tableWidget.setItem(1, 0, newItem) # # # Create a new entry, set the background color, add to the specified row of the table # newItem = QTableWidgetItem('男' # newItem.setFont(QFont('Times', 12, QFont.Black)) # tableWidget.setItem(1, 1, newItem) # # # Create a new entry, set the background color, add to the specified row of the table # newItem = QTableWidgetItem('150') # newItem.setFont(QFont('Times', 12, QFont.Black)) # tableWidget.setItem(1, 2, newItem) # # newItem = QTableWidgetItem('王五') ##Add font bold, black font # newItem.setFont(QFont('Times',12,QFont.Black)) # tableWidget.setItem(2, 0, newItem) # # # Create a new entry, set the background color, add to the specified row of the table # newItem = QTableWidgetItem('female') # newItem.setFont(QFont('Times', 12, QFont.Black)) # tableWidget.setItem(2, 1, newItem) # # # Create a new entry, set the background color, add to the specified row of the table # newItem = QTableWidgetItem('175') # newItem.setFont(QFont('Times', 12, QFont.Black)) # Set the alignment of cell text #newItem.setTextAlignment(Qt.AlignRight|Qt.AlignBottom) #tableWidget.setItem(2, 2, newItem) # Sort by weight #Qt.DescendingOrderDescending #Qt.AscEndingOrder ascending #tableWidget.sortItems(2,Qt.DescendingOrder) #Merge Cells #tableWidget.setSpan(2,0,4,1) #Set the size of the cell #Set the cell width of the first column to 150 #tableWidget.setColumnWidth(0,150) #Set the cell height of the first row to 120 #tableWidget.setRowHeight(0,120) #分线 is not displayed in the table #tableWidget.setShowGrid(False) #Hide vertical head label #tableWidget.verticalHeader().setVisible(False) self.setLayout(conLayout) if __name__ == '__main__': app = QApplication(sys.argv) example = Table() example.show() sys.exit(app.exec_())

初期動作、効果は以下の通りです
ここに写真の説明を書いてください
最適化1: セルのテキストの色を設定して、最初の行の3つのテキストの色を赤に設定します

newItem.setForeground(QBrush(QColor(255, 0, 0)))

ここに写真の説明を書いてください
最適化2 : 太字フォント

#Set font type, size number, color newItem.setFont(QFont('Times',12,QFont.Black))
  • ここに写真の説明を書いてください
    最適化3: セルの並べ替え方法を設定する
from PyQt5.QtCore import Qt # Sort by weight #Qt.DescendingOrderDescending #Qt.AscEndingOrder ascending tableWidget.sortItems(2,Qt.DescendingOrder)

ここに写真の説明を書いてください
最適化4 :セルのテキスト配置
ここで、WangWuのウェイトのテキスト配置を右下隅に変更しました。

# Set the alignment of cell text (bottom right) newItem.setTextAlignment(Qt.AlignRight|Qt.AlignBottom) tableWidget.setItem(2, 2, newItem)

ここに写真の説明を書いてください
最適化5: セルを結合します
テーブルの最初の行の最初の列のセルを5行1列を占めるように変更します

#Merge Cells tableWidget.setSpan(2,0,5,1)
  • ここに写真の説明を書いてください
    最適化6: セルのサイズを設定します
    ここでは、最初の線幅が150に設定され、高さが120に設定されています。
#Set the cell width of the first column to 150 tableWidget.setColumnWidth(0,150) #Set the cell height of the first row to 120 tableWidget.setRowHeight(0,120)

ここに写真の説明を書いてください
最適化7 :テーブルに分割線を表示しない
QTableWidgetクラスのsetShowGrid()関数は、QTableViewクラスから継承され、テーブルの分割行を表示するかどうかを設定するために使用されます。デフォルトの表示分割線

#分线 is not displayed in the table tableWidget.setShowGrid(False)

ここに写真の説明を書いてください
最適化8 :セルに画像を追加する
セルに画像を追加して画像の説明情報を表示することもできます。コードは次のとおりです。
ここでは、画像がWangWuの重みのセルに配置されています。

#add pictures newItem = QTableWidgetItem(QIcon('./images/bao1.png'), 'Backpack') tableWidget.setItem(2, 2, newItem)

ここに写真の説明を書いてください

例4:セル内の画像の表示

import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * class Table(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): #Set title and initial size self.setWindowTitle('QTableWidget example') self.resize(1000 ,900) #设置Layout, initial form 5*3 conLayout = QHBoxLayout() table= QTableWidget(5,3) #设置表水平头标签 table.setHorizontalHeaderLabels(['image 1', 'image 2', 'image 3']) #Set non-editable mode table.setEditTriggers( QAbstractItemView.NoEditTriggers) #Set the size of the image table.setIconSize(QSize(300 ,200)) #Set all row and column width and height values ​​to be the same as the image size For i in range(3): # Let the column width and the picture be the same table.setColumnWidth(i , 300) For i in range(5): # Let the line height be the same as the picture table.setRowHeight(i , 200) for k in range(15): i = k/ 3 j = k % 3 #Instance table window entry item = QTableWidgetItem() #图片 is selected when the user clicks on the form item.setFlags(Qt.ItemIsEnabled) #图片路径设置和图片加载 icon = QIcon(r'.imagesao%d.png' % k) item.setIcon(QIcon(icon)) #output the current sequence number of the item print('e/icons/%d.png i=%d j=%d' % (k, i, j)) #Load the entry into the appropriate rank table.setItem(i, j, item) conLayout.addWidget(table) self.setLayout(conLayout) if __name__ == '__main__': app = QApplication(sys.argv) example = Table() example.show() sys.exit(app.exec_())

効果は以下の通りです
ここに写真の説明を書いてください

例5:右クリックメニューのサポート

import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * class Table(QWidget): def __init__(self): super(Table, self).__init__() self.initUI() def initUI(self): # Set the title and initial size self.setWindowTitle('QTableWidget demo') self.resize(500, 300) #Horizontal layout, initial table 5*3, added to the layout layout = QHBoxLayout() self.tableWidget = QTableWidget(5, 3) layout.addWidget(self.tableWidget) # Set the header label in the horizontal direction of the table self.tableWidget.setHorizontalHeaderLabels([ 'name', 'gender', 'weight'] # Set the horizontal direction to automatically expand and fill the window self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) # Add data to the specified rank newItem = QTableWidgetItem('张三') self.tableWidget.setItem(0, 0, newItem) newItem = QTableWidgetItem('male') self.tableWidget.setItem(0, 1, newItem) newItem = QTableWidgetItem('160') self.tableWidget.setItem(0, 2, newItem) newItem = QTableWidgetItem('李四') self.tableWidget.setItem(1, 0, newItem) newItem = QTableWidgetItem('female') self.tableWidget.setItem(1, 1, newItem) newItem = QTableWidgetItem('120') self.tableWidget.setItem(1, 2, newItem) # Allow right button to generate menu self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu) # Bind the right-click menu to the slot function generateMenu self.tableWidget.customContextMenuRequested.connect(self.generateMenu) self.setLayout(layout) def generateMenu(self, pos): # Calculate how many pieces of data, default -1, row_num = -1 for i in self.tableWidget.selectionModel().selection().indexes(): row_num = i.row() # There are only two valid data in the table, so only the first two lines support the right-click pop-up menu. if row_num <2: menu = QMenu() Item1 = menu.addAction(u'option one') Item2 = menu.addAction(u'option two') Item3 = menu.addAction(u'option three') action = menu.exec_(self.tableWidget.mapToGlobal(pos)) # Display the data text of the selected line if action == item1: Print('You selected option one, the current line text is: ', self.tableWidget.item(row_num, 0).text(), self.tableWidget.item(row_num, 1).text(), self.tableWidget.item(row_num, 2).text()) if action == item2: Print('You selected option two, the current line text is: ', self.tableWidget.item(row_num, 0).text(), self.tableWidget.item(row_num, 1).text(), self.tableWidget.item(row_num, 2).text()) if action == item3: Print('You selected option three, the current line text content is: ', self.tableWidget.item(row_num, 0).text(), self.tableWidget.item(row_num, 1).text(), self.tableWidget.item(row_num, 2).text()) if __name__ == '__main__': app = QApplication(sys.argv) example = Table() example.show() sys.exit(app.exec_())

ここに写真の説明を書いてください

関連ドキュメントとダウンロードアドレス

https://download.csdn.net/download/jia666666/10609488

---------------------この記事はjia666666CSDNブログからのものです。全文アドレスは、https://blog.csdn.net/jia666666/articleをクリックしてください。 / details / 81627589?utm_source = copy