在PyQt中對QTableView新增右鍵選單

2021-07-10 05:38:51 字數 1580 閱讀 9698

上面的軟體,最左側是qlist,中間是qlabelview,準備給中間的**加個右鍵選單,主要**如下

self.view

.setcontextmenupolicy(qt.customcontextmenu) # 右鍵選單,如果不設為customcontextmenu,無法使用customcontextmenurequested

self.view

.customcontextmenurequested

.connect(self.showcontextmenu)

def

showcontextmenu

(self):

# 建立右鍵選單

self.view.contextmenu = qmenu(self)

self.actiona = self.view.contextmenu.addaction(u'動作a')

# self.actiona = self.view.contextmenu.exec_(self.maptoglobal(pos)) # 1

self.view.contextmenu.popup(qcursor.pos()) # 2選單顯示的位置

self.actiona.triggered.connect(self.actionhandler)

# self.view.contextmenu.move(self.pos()) # 3

self.view.contextmenu.show()

defactionhandler

(self):

print

"成功"

建立選單很快,主要是位置問題,可以看到**中關於位置的就有三條,1和3效果一樣,他獲取到的位置是在**中的位置,選單卻出現在整個軟體的相對位置上,只有2獲得的位置是準確的

def

showcontextmenu

(self, pos):

# 建立右鍵選單

self.view.contextmenu = qmenu(self)

self.actiona = self.view.contextmenu.addaction(u'動作a')

# self.actiona = self.view.contextmenu.exec_(self.maptoglobal(pos)) # 1

self.view.contextmenu.popup(qcursor.pos()) # 2選單顯示的位置

self.actiona.triggered.connect(self.actionhandler)

# self.view.contextmenu.move(self.pos() + pos) # 3

self.view.contextmenu.show()

defactionhandler

(self):

print

"成功"

在linux中安裝pyqt

可直接通過命令列安裝pyqt 通過search命令檢視在倉庫中關於qt的安裝源的具體名稱 apt cache search qt通過apt get命令直接安裝 sudo apt get install python qt4通過以下命令檢視qt版本 qmake v有時候會出現以下錯誤 qmake co...

PyQtGraph在pyqt中的應用及安裝過程

1.pyqtgraph簡介 pyqtgraph的主要用途 1 為資料 繪圖 等提供快速 可互動圖形顯示。2 提供快速開發應用的工具。2.pyqtgraph的安裝 pip install pyqtgraph 安裝完成之後執行如下 可以看到官方示例。import pyqtgraph.examplespy...

PyQt5中對單元格進行排序

sortitems 列索引,排序型別 import sys from pyqt5 import qtcore from pyqt5.qtcore import qt from pyqt5.qtgui import from pyqt5.qtwidgets import class columnsor...