【问题标题】:Qt Syntax conversion from C++ to PyQt从 C++ 到 PyQt 的 Qt 语法转换
【发布时间】:2016-07-01 13:36:59
【问题描述】:

我正在尝试用 python 重写一些 PyQt C++ 代码。 我已经多次进行这种类型的语法转换,但没有像这样的子类示例。此 C++ 代码旨在允许您将组合框添加到 QTableWidget 标题,以类似于 Excel 标题过滤器。 我可以转换大部分逻辑,但是对于这个示例,我需要有关 python 中的子类语法的帮助。任何帮助表示赞赏。

MyHorizontalHeader(QWidget *parent = 0) : QHeaderView(Qt::Horizontal, parent)
{
     connect(this, SIGNAL(sectionResized(int, int, int)), this, 
             SLOT(handleSectionResized(int)));
     connect(this, SIGNAL(sectionMoved(int, int, int)), this, 
             SLOT(handleSectionMoved(int, int, int)));
     setMovable(true);
}

void showEvent(QShowEvent *e)
{
    for (int i=0;i<count();i++) {
       if (!boxes[i]) {
          QComboBox *box = new QComboBox(this);
          boxes[i] = box;
       }
       boxes[i]->setGeometry(sectionViewportPosition(i), 0, 
                                sectionSize(i) - 5, height());
       boxes[i]->show();
    }
    QHeaderView::showEvent(e);
 }

void handleSectionResized(int i)
{
    for (int j=visualIndex(i);j<count();j++) {
        int logical = logicalIndex(j);
        boxes[logical]->setGeometry(sectionViewportPosition(logical), 0, 
                                       sectionSize(logical) - 5, height());
    }
}

void handleSectionMoved(int logical, int oldVisualIndex, int newVisualIndex)
{
    for (int i=qMin(oldVisualIndex, newVisualIndex);i<count();i++){
        int logical = logicalIndex(i);
        boxes[logical]->setGeometry(sectionViewportPosition(logical), 0, 
                                       sectionSize(logical) - 5, height());
    }
}

void scrollContentsBy(int dx, int dy)
{
   QTableWidget::scrollContentsBy(dx, dy);
   if (dx != 0)
      horizHeader->fixComboPositions();
}

void fixComboPositions()
{
    for (int i=0;i<count();i++)
        boxes[i]->setGeometry(sectionViewportPosition(i), 0, 
                                 sectionSize(i) - 5, height());
}

本示例源码最初来自http://blog.qt.io/blog/2012/09/28/qt-support-weekly-27-widgets-on-a-header/

我希望最终创建一个自定义子类,我可以在“Qt Designer”中为我的 QTableWidgets 推广,从而我可以使用组合框过滤器自定义 QTableWidget QHeaderView。

【问题讨论】:

  • 您能否先移植您所做了解的所有内容,以便更轻松地查看您遇到问题的具体部分?
  • 这是我遇到问题的行... MyHorizo​​ntalHeader(QWidget *parent = 0) : QHeaderView(Qt::Horizo​​ntal, parent)

标签: python c++ pyqt pyside


【解决方案1】:

PyQt/PySide 中的子类化是这样开始的:

class MyHorizontalHeader(QHeaderView): 

    def __init__(self, parent=None):
        super(MyHorizontalHeader, self).__init__(Qt.Horizontal, parent)

    def otherMethod(self):
        ...
    ...

第一行定义类的名称和潜在的继承。

__init__ 方法在创建类的实例时被调用。它总是需要调用它继承自的类的__init__ 方法(这是PyQt/PySide 特有的),这是通过super 完成的。

【讨论】:

    猜你喜欢
    • 2017-11-06
    • 2021-11-28
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 2017-05-13
    • 2017-03-28
    • 1970-01-01
    相关资源
    最近更新 更多