我正在尝试使用函数QTreeWidget.findItems来查找完全匹配(该项被命名为“Things”)我看到了一个使用此示例的示例... Qt.MatchExactly ...作为'匹配标志'。即使我从PyQt5导入了Qt模块,也找不到MatchExactly。我通过在PyQt5中导入QtCore中的另一个Qt模块来实现它。但这是经过几天的戳了几天,猜测和阅读stackOverFlow的帖子。
我的问题是 - 如何知道哪些模块包含(因此必须导入)我需要的东西?我怎么知道Qt.MatchExactly在PyQt5.QtCore.Qt模块中(而不是在PyQt5.Qt模块中)?
这是我的代码:注意它在QtDesigner .ui文件中读取,因此它不适合你。但是你运行这段代码不是重点。
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QMainWindow, QApplication, QTreeWidgetItem
from PyQt5 import uic, QtWidgets, Qt #<<flags are not here
from PyQt5 import QtCore
from PyQt5.QtCore import Qt #<<<this is where i found the match flag "MatchExactly"
qtCreatorFile = "Main2.ui" # Enter qt Designer file here.
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class MyApp(QMainWindow):
def __init__(self):
super(MyApp, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.InitModelContentTree()
def InitModelContentTree (self):
modelContentTree = self.ui.ModelContentTree
ThingsItemList = modelContentTree.findItems("Things", Qt.MatchExactly)
ThingsItem = ThingsItemList[0]
QTreeWidgetItem(ThingsItem, ["New Thing"])
print("pause")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
我希望有一个解码器环,一些基本的东西,我想念。我证明这是一个非常糟糕,非常低效的猜测者。
实际上Qt.MatchExactly在Qt中,但你必须以另一种方式导入它:
from PyQt5 import Qt
# ...
ThingsItemList = modelContentTree.findItems("Things", Qt.Qt.MatchExactly)
TL; DR
Qt子模块是一个伪模块,允许访问任何模块,例如别名,例如它类似于:
from PyQt5 import QtCore as Qt
from PyQt5 import QtGui as Qt
from PyQt5 import QtWidgets as Qt
# ...
# The same for all submodules
例如,可以检查Qt.MatchExactly:
from PyQt5 import Qt, QtCore
assert(QtCore.Qt.MatchExactly == Qt.Qt.MatchExactly)
所以一般来说导入如下:
from PyQt5 import somemodule
somemodule.someclass
它相当于:
from PyQt5 import Qt
Qt.someclass
如何知道一个类属于哪个子模块?:嗯,如果你有一个可以像pycharm那样进行自我报告的IDE,那么任务很简单,因为IDE本身就是这样做的。但是,如果我无法访问IDE,则另一种选择是使用Qt的文档,例如Qt::MatchExactly的文档在此链接中,第一部分是下表:
并观察Qt += core
,因此该文档的所有元素都属于Qt的核心子模块,在PyQt / PySide中对应于QtCore(一般来说,如果Qt的文档在Qt += mymodule
中指示PyQt / PySide中的QtMyModule
)。也就是C的Qt::MatchExactly
++对应于python中的Qt.MatchExactly
。所以最后你应该使用:
from PyQt5 import QtCore
QtCore.Qt.MatchExactly