我正在使用 PyQt 并且对 OOP 有足够的了解,可以轻松地使用 Python。但是,文档和有用的论坛帖子都是用 C++ 编写的。我知道最好的方法可能是重新学习 C++。我正在尝试,但要花很长时间来筛选教程并找到我需要的信息,主要是因为我对术语的理解不够,不知道去哪里找。
在特定论坛中post类实现的方法中有一段内容如下:
void SetTextInteraction(bool on, bool selectAll = false)
{
if(on && textInteractionFlags() == Qt::NoTextInteraction)
{
// switch on editor mode:
setTextInteractionFlags(Qt::TextEditorInteraction);
// manually do what a mouse click would do else:
setFocus(Qt::MouseFocusReason); // this gives the item keyboard focus
setSelected(true); // this ensures that itemChange() gets called when we click out of the item
if(selectAll) // option to select the whole text (e.g. after creation of the TextItem)
{
QTextCursor c = textCursor();
c.select(QTextCursor::Document);
setTextCursor(c);
}
}
else if(!on && textInteractionFlags() == Qt::TextEditorInteraction)
{
// turn off editor mode:
setTextInteractionFlags(Qt::NoTextInteraction);
// deselect text (else it keeps gray shade):
QTextCursor c = this->textCursor();
c.clearSelection();
this->setTextCursor(c);
clearFocus();
}
}
我不明白的部分在这里:
QTextCursor c = textCursor();
c.select(QTextCursor::Document);
setTextCursor(c);
这个特定部分的等效 Python 代码是什么?出于某种原因,我认为第一行可能是 c = QTextCursor.textCursor()
,因为 QTextCursor
类的方法 textCursor
的结果是被分配给c
,但是似乎没有textCursor
方法。我也无法理解这里发生了什么:
QTextCursor c = this->textCursor();
c.clearSelection();
this->setTextCursor(c);
用文字解释正在发生的事情会很有用,因为这有助于术语位。如果能推荐一些资源来理解这些特定的代码片段,我们也将不胜感激。
最佳答案
我的 Python 和 PyQt 生锈了,但这里有一个可能存在语法小错误的翻译:
def SetTextInteraction(self, on, selectAll):
if on and self.textInteractionFlags() == Qt.NoTextInteraction:
self.setTextInteractionFlags(Qt.TextEditorInteraction)
self.setFocus(Qt.MouseFocusReason)
self.setSelected(True)
if selectAll:
c = self.textCursor()
c.select(QTextCursor.Document)
self.setTextCursor(c)
elif not on and self.textInteractionFlags() == Qt.TextEditorInteraction:
self.setTextInteractionFlags(Qt.NoTextInteraction)
c = self.textCursor()
c.clearSelection()
self.setTextCursor(c)
self.clearFocus()
您对链接到的代码中发生的事情感到困惑的原因有两个:
C++ 在编译时处理隐式范围解析; Python 需要显式声明。首先检查本地范围(成员函数),然后是周围的类,然后(我相信)本地翻译单元/本地非成员函数,最后向上命名空间/范围层次结构,直到找到被引用的函数或变量。
textCursor
是TextItem
的父类的成员函数.打电话textCursor()
与调用this->textCursor()
相同,在 Python 中是self.textCursor()
.提供的代码混合了
this
的显式用法隐式调用。使用this
在 C++ 中不必要的地方被认为是错误的形式,并使其看起来好像textCursor()
与this->textCursor()
不同.希望在阅读我提供的 Python 版本时,您会发现两者没有区别。
future 的资源
C++ tag有很好的 C++ 常见问题解答链接。我建议漫步 C++ Super-FAQ .你会学到你没想到你需要知道的事情,你不知道但不清楚的事情将会得到澄清。还有The Definitive C++ Book Guide and List在这里。
对于 PyQt 开发,Mark Summerfield 的 Rapid GUI Programming with Python and Qt是一个很好的工作代码引用。
关于python - C++ Qt Snippet 的等效 PyQt 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37751197/