如何在Q中以编程方式生成水平线

2024-03-28 13:33:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在想如何在Qt中画一条水平线。这很容易在设计器中创建,但我想以编程方式创建一个。我做了一些谷歌搜索,在一个ui文件中查看了xml,但还没有发现任何问题。

这是来自ui文件的xml的外观:

  <widget class="Line" name="line">
   <property name="geometry">
    <rect>
     <x>150</x>
     <y>110</y>
     <width>118</width>
     <height>3</height>
    </rect>
   </property>
   <property name="orientation">
    <enum>Qt::Horizontal</enum>
   </property>
  </widget>

Tags: 文件namerectui编程方式propertyenum
2条回答

水平线或垂直线只是设置了一些属性的QFrame。在C++中,生成一行的代码看起来像这样:

line = new QFrame(w);
line->setObjectName(QString::fromUtf8("line"));
line->setGeometry(QRect(320, 150, 118, 3));
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);

下面是另一个使用PySide的解决方案:

from PySide.QtGui import QFrame


class QHLine(QFrame):
    def __init__(self):
        super(QHLine, self).__init__()
        self.setFrameShape(QFrame.HLine)
        self.setFrameShadow(QFrame.Sunken)


class QVLine(QFrame):
    def __init__(self):
        super(QVLine, self).__init__()
        self.setFrameShape(QFrame.VLine)
        self.setFrameShadow(QFrame.Sunken)

然后可用作(例如):

from PySide.QtGui import QApplication, QWidget, QGridLayout, QLabel, QComboBox


if __name__ == "__main__":
    app = QApplication([])
    widget = QWidget()
    layout = QGridLayout()

    layout.addWidget(QLabel("Test 1"), 0, 0, 1, 1)
    layout.addWidget(QComboBox(), 0, 1, 1, 1)
    layout.addWidget(QHLine(), 1, 0, 1, 2)
    layout.addWidget(QLabel("Test 2"), 2, 0, 1, 1)
    layout.addWidget(QComboBox(), 2, 1, 1, 1)

    widget.setLayout(layout)
    widget.show()
    app.exec_()

结果如下:

Example of QHLine on Windows 10

相关问题 更多 >