ZetCode GUI 教程(三十六)

原文:ZetCode 协议:CC BY-NC-SA 4.0 布局管理 原文: http:zetcodeguivbqyotolayoutmanagement 在 V

原文:ZetCode

协议:CC BY-NC-SA 4.0

布局管理

原文: http://zetcode/gui/vbqyoto/layoutmanagement/

在 Visual Basic Qyoto 编程教程的这一部分中,我们将介绍布局管理器。

在设计应用的 GUI 时,我们决定要使用哪些组件以及如何在应用中组织这些组件。 为了组织我们的组件,我们使用专门的不可见对象,称为布局管理器。 Qyoto 中有多个选项。 我们可以使用绝对定位,内置布局管理器或创建自定义布局管理器。 我们还可以使用 Qt Designer 直观地构建布局。

Qyoto 有一些重要的内置布局管理器。 QVBoxLayout类垂直排列小部件。 QHBoxLayout水平排列小部件。 QGridLayout类将小部件布置在网格中。 网格布局是最灵活的布局管理器。 盒子布局相互嵌套以创建复杂的布局。

绝对定位

在大多数情况下,程序员应使用布局管理器。 在某些情况下,我们可以使用绝对定位。 在绝对定位中,程序员以像素为单位指定每个小部件的位置和大小。 如果我们调整窗口大小,则小部件的大小和位置不会改变。 在各种平台上,应用看起来都不同,在 Linux 上看起来不错,在 Mac OS 上看起来不太正常。 在我们的应用中更改字体可能会破坏布局。 如果我们将您的应用翻译成另一种语言,则必须重做布局。 对于所有这些问题,仅在有理由时才使用绝对定位。

' ZetCode Mono Visual Basic Qt tutorial
'
' In this program, we lay out widgets
' using absolute positioning
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QMainWindow

    Dim bardejov As QPixmap
    Dim rotunda As QPixmap 
    Dim mincol As QPixmap

    Public Sub New()

        Me.SetWindowTitle("Absolute")

        Me.InitUI()

        Me.Resize(300, 280)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        SetStyleSheet("QWidget { background-color: #414141 }")

        Try 
            bardejov = New QPixmap("bardejov.jpg")
            rotunda = New QPixmap("rotunda.jpg")
            mincol = New QPixmap("mincol.jpg")
        Catch e As Exception
            Console.WriteLine(e.Message)
            Environment.Exit(1)
        End Try

        Dim barLabel As New QLabel(Me)
        barLabel.SetPixmap(bardejov)
        barLabel.SetGeometry(20, 20, 120, 90)

        Dim rotLabel As New QLabel(Me)
        rotLabel.SetPixmap(rotunda)
        rotLabel.SetGeometry(40, 160, 120, 90)

        Dim minLabel As New QLabel(Me)
        minLabel.SetPixmap(mincol)
        minLabel.SetGeometry(170, 50, 120, 90)

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在此示例中,我们使用绝对定位显示了三幅图像。

Dim barLabel As New QLabel(Me)
barLabel.SetPixmap(bardejov)

QLabel小部件用于保存图像。

barLabel.SetGeometry(20, 20, 120, 90)

我们使用SetGeometry()方法将标签放置在窗口上的x = 20y = 20处。 图片大小为120x90

调整窗口大小时,标签将保留其初始大小。

图:绝对定位

按钮示例

在下面的示例中,我们将在窗口的右下角放置两个按钮。

' ZetCode Mono Visual Basic Qt tutorial
'
' In this program, use box layouts
' to position two buttons in the
' bottom right corner of the window
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Public Sub New()

        Me.SetWindowTitle("Buttons")

        Me.InitUI()

        Me.Resize(300, 150)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        Dim vbox As New QVBoxLayout(Me)
        Dim hbox As New QHBoxLayout

        Dim ok As New QPushButton("OK", Me)
        Dim apply As New QPushButton("Apply", Me)

        hbox.AddWidget(ok, 1, Qt.AlignmentFlag.AlignRight)
        hbox.AddWidget(apply)

        vbox.AddStretch(1)
        vbox.AddLayout(hbox)

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

我们使用嵌套框布局来获得我们想要的布局。

Dim vbox As New QVBoxLayout(Me)
Dim hbox As New QHBoxLayout

我们使用一个垂直框和一个水平框。

Dim ok As New QPushButton("OK", Me)
Dim apply As New QPushButton("Apply", Me)

这是两个将进入窗口右下角的按钮。

hbox.AddWidget(ok, 1, Qt.AlignmentFlag.AlignRight)

我们将确定按钮放入水平框中。 第二个参数是stretch因子。 它将扩大分配给“确定”按钮的区域。 它会占用所有可用空间。 在此区域内,按钮向右对齐。

vbox.AddStretch(1)

这条线创建了一个垂直扩展的白色空间,它将带有按钮的水平框推到底部。

vbox.AddLayout(hbox)

水平框嵌套在垂直框中。

图:按钮示例

Windows 示例

以下是嵌套框布局更复杂的示例。

' ZetCode Mono Visual Basic Qt tutorial
'
' In this program, use box layouts
' to create a windows example
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Public Sub New()

        Me.SetWindowTitle("Windows")

        Me.InitUI()

        Me.Resize(350, 300)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        Dim vbox As New QVBoxLayout(Me)

        Dim vbox1 As New QVBoxLayout
        Dim hbox1 As New QHBoxLayout
        Dim hbox2 As New QHBoxLayout

        Dim windLabel As New QLabel("Windows", Me)
        Dim edit As New QTextEdit(Me)
        edit.SetEnabled(False)

        Dim activate As New QPushButton("Activate", Me)
        Dim close As New QPushButton("Close", Me)
        Dim help As New QPushButton("Help", Me)
        Dim ok As New QPushButton("OK", Me)

        vbox.AddWidget(windLabel)

        vbox1.AddWidget(activate)
        vbox1.AddWidget(close, 0, AlignmentFlag.AlignTop)
        hbox1.AddWidget(edit)
        hbox1.AddLayout(vbox1)

        vbox.AddLayout(hbox1)

        hbox2.AddWidget(help)
        hbox2.AddStretch(1)
        hbox2.AddWidget(ok)

        vbox.AddLayout(hbox2, 1)

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在此布局中,我们使用两个垂直和水平框。

Dim vbox As New QVBoxLayout(Me)

这是示例的基本布局。

vbox.AddWidget(windLabel)

首先是标签小部件。 它只是转到垂直框的顶部。

vbox1.AddWidget(activate)
vbox1.AddWidget(close, 0, AlignmentFlag.AlignTop)
hbox1.AddWidget(edit)
hbox1.AddLayout(vbox1)

vbox.AddLayout(hbox1)

在窗口的中心部分,我们有一个文本编辑小部件和两个垂直排列的按钮。 这些按钮进入垂直框。 在此垂直框中,按钮与顶部对齐。 垂直框和文本编辑进入水平框。 该水平框转到标签窗口小部件正下方的基本垂直框。

hbox2.AddWidget(help)
hbox2.AddStretch(1)
hbox2.AddWidget(ok)

vbox.AddLayout(hbox2, 1)

帮助和确定按钮进入另一个水平框。 这两个按钮之间有一个扩大的空白区域。 同样,水平框转到基本垂直框。

图:窗口示例

新文件夹示例

在最后一个示例中,我们使用QGridLayout管理器创建“新文件夹”布局示例。

' ZetCode Mono Visual Basic Qt tutorial
'
' In this program, use the QGridLayout
' to create a New Folder example
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Public Sub New()

        Me.SetWindowTitle("New Folder")

        Me.InitUI()

        Me.Resize(350, 300)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        Dim grid As New QGridLayout(Me)

        Dim nameLabel As New QLabel("Name", Me)
        Dim nameEdit As New QLineEdit(Me)
        Dim text As New QTextEdit(Me)
        Dim okButton As New QPushButton("OK", Me)
        Dim closeButton As New QPushButton("Close", Me)

        grid.AddWidget(nameLabel, 0, 0)
        grid.AddWidget(nameEdit, 0, 1, 1, 3)
        grid.AddWidget(text, 1, 0, 2, 4)
        grid.SetColumnStretch(1, 1)
        grid.AddWidget(okButton, 4, 2)
        grid.AddWidget(closeButton, 4, 3)

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在我们的示例中,我们有一个标签,一行编辑,一个文本编辑和两个按钮。

Dim grid As New QGridLayout(Me)

我们创建QGridLayout管理器的实例。

grid.AddWidget(nameLabel, 0, 0)

我们将标签小部件放置在网格的第一个单元格中。 单元格从 0 开始计数。最后两个参数是行号和列号。

grid.AddWidget(nameEdit, 0, 1, 1, 3)

线编辑窗口小部件位于第一行第二列。 最后两个参数是行跨度和列跨度。 在水平方向上,小部件将跨越三列。

grid.SetColumnStretch(1, 1)

该方法的参数是列号和拉伸因子。 在这里,我们将拉伸因子 1 设置到第二列。 这意味着此列将占用所有剩余空间。 之所以这样设置,是因为我们希望按钮保持其初始大小。

图:新文件夹 example

在 Visual Basic Qyoto 教程的这一部分中,我们提到了小部件的布局管理。

Windows API 简介

原文: http://zetcode/gui/winapi/introduction/

这是 Windows API 教程。 本教程将教您使用 C 编程语言进行 Windows API 编程的基础知识和更高级的主题。 它不涵盖 MFC。 (Microsoft 基础类是一个广泛使用的 C++ 库,用于在 Windows 上开发 C++ 应用。)本教程已在 Windows 7 上创建并经过测试。示例使用 Pelles C 编译器构建。如果您打算阅读本教程,建议您下载并安装此编译器。 (这是一个免费软件。)如果要使用其他编译器,请确保它支持 C99 标准。

Windows API

Windows API 是用于创建 Windows 应用的应用编程接口。 为了创建 Windows 应用,我们必须下载 Windows SDK。 (以前称为 Platform SDK。)SDK(软件开发工具包)包含使用 Windows API 开发应用的头文件,库,示例,文档和工具。 Windows API 是为 C 和 C++ 编程语言创建的。 这是创建 Windows 应用的最直接方法。 (如果我们安装 Pelles C,则已经包含 Windows SDK。)

Windows API 可以分为几个区域:

  • 基础服务
  • 安全
  • 图形
  • 用户界面
  • 多媒体
  • Windows 外壳
  • 互联网

基本服务提供对 Windows 上基本资源的访问。 这些包括文件系统,设备,进程,线程,注册表或错误处理。安全区域提供功能,接口,对象和其他编程元素,用于认证,授权,加密和其他与安全相关的任务。图形子系统提供了将图形内容输出到监视器,打印机和其他输出设备的功能。用户界面提供创建窗口和控件的功能。多媒体组件提供了用于处理视频,声音和输入设备的工具。 Windows Shell 界面的功能允许应用访问操作系统外壳提供的功能。网络服务提供对 Windows OS 网络功能的访问。

Windows API 是 Windows 操作系统编程接口的抽象规范。 它由函数,联合,结构,数据类型,宏,常量和其他编程元素的声明组成。 Windows API 主要由 MSDN(Microsoft 开发者网络)描述,并且位于 Windows C 标头中。 Windows API 函数的正式实现位于动态库(DLL)中。 例如,Windows 系统目录中的kernel32.dlluser32.dllgdi32.dllshell32.dll。 Windows API 有第三方实现:最著名的是 Wine 项目和 ReactOS 项目。

Windows API 是一个动态实体。 随着 Windows OS 的每个新版本和新 Service Pack 的出现,功能数量不断增加。 服务器版本和操作系统的桌面版本之间也存在一些重要区别。 某些功能尚未正式记录。

Pelles C

Pelles C 是用于 C 编程语言的出色 C 编译器和集成开发环境(IDE)。 它同时支持 32 位 Windows(x86)和 64 位 Windows(x64)。 它实现了 C99 和 C11 标准。 Pelles C 具有集成的资源编辑器,位图,图标和光标编辑器以及十六进制转储编辑器。 它由瑞典开发商 Pelle Orinius 开发。 它带有 Windows SDK,因此我们可以立即开始创建 Windows 应用,而无需进行进一步的安装。

Pelles C 是免费软件。 我们可以从以下链接下载 Pelles C: Pelles C 下载。

没有目标架构的错误

为了创建 Windows API 程序,我们必须启用 Microsoft 扩展。 默认情况下未启用它们。 因此,编译器将产生以下错误消息:fatal error #1014: #error: "No target architecture"。 要启用 Microsoft 扩展,我们转到项目选项,然后选择“编译器”选项卡。 在此选项卡中,我们选中“启用 Microsoft 扩展”框。

MSDN

MSDN(Microsoft 开发者网络)是 Windows 开发的中央门户。 它是与使用 Microsoft 工具开发 Windows 应用有关的大量材料。 (不包括 Qt4 或 Java Swing 之类的第三方软件。)它是 Windows API 的最完整参考。 以下两个链接是 Windows API 参考的良好入口点:桌面应用开发文档和 Windows API 列表。

本章是 Windows API 的简介。

PyQt5 中的自定义小部件

原文: http://zetcode/gui/pyqt5/customwidgets/

PyQt5 具有丰富的小部件集。 但是,没有工具包可以向程序员提供在其应用中可能需要的所有小部件。 工具箱通常仅提供最常见的窗口小部件,例如按钮,文本窗口小部件或滑块。 如果需要更专业的小部件,我们必须自己创建它。

使用工具箱提供的绘图工具创建自定义窗口小部件。 有两种基本的可能性:程序员可以修改或增强现有的小部件,或者可以从头开始创建自定义小部件。

刻录小部件

这是一个小部件,我们可以在 Nero,K3B 或其他 CD/DVD 刻录软件中看到。

customwidget.py

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

In this example, we create a custom widget.

Author: Jan Bodnar
Website: zetcode 
Last edited: August 2017
"""

from PyQt5.QtWidgets import (QWidget, QSlider, QApplication, 
    QHBoxLayout, QVBoxLayout)
from PyQt5.QtCore import QObject, Qt, pyqtSignal
from PyQt5.QtGui import QPainter, QFont, QColor, QPen
import sys

class Communicate(QObject):

    updateBW = pyqtSignal(int)

class BurningWidget(QWidget):

    def __init__(self):      
        super().__init__()

        self.initUI()

    def initUI(self):

        self.setMinimumSize(1, 30)
        self.value = 75
        self.num = [75, 150, 225, 300, 375, 450, 525, 600, 675]

    def setValue(self, value):

        self.value = value

    def paintEvent(self, e):

        qp = QPainter()
        qp.begin(self)
        self.drawWidget(qp)
        qp.end()

    def drawWidget(self, qp):

        MAX_CAPACITY = 700
        OVER_CAPACITY = 750

        font = QFont('Serif', 7, QFont.Light)
        qp.setFont(font)

        size = self.size()
        w = size.width()
        h = size.height()

        step = int(round(w / 10))

        till = int(((w / OVER_CAPACITY) * self.value))
        full = int(((w / OVER_CAPACITY) * MAX_CAPACITY))

        if self.value >= MAX_CAPACITY:

            qp.setPen(QColor(255, 255, 255))
            qp.setBrush(QColor(255, 255, 184))
            qp.drawRect(0, 0, full, h)
            qp.setPen(QColor(255, 175, 175))
            qp.setBrush(QColor(255, 175, 175))
            qp.drawRect(full, 0, till-full, h)

        else:

            qp.setPen(QColor(255, 255, 255))
            qp.setBrush(QColor(255, 255, 184))
            qp.drawRect(0, 0, till, h)

        pen = QPen(QColor(20, 20, 20), 1, 
            Qt.SolidLine)

        qp.setPen(pen)
        qp.setBrush(Qt.NoBrush)
        qp.drawRect(0, 0, w-1, h-1)

        j = 0

        for i in range(step, 10*step, step):

            qp.drawLine(i, 0, i, 5)
            metrics = qp.fontMetrics()
            fw = metrics.width(str(self.num[j]))
            qp.drawText(i-fw/2, h/2, str(self.num[j]))
            j = j + 1

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):      

        OVER_CAPACITY = 750

        sld = QSlider(Qt.Horizontal, self)
        sld.setFocusPolicy(Qt.NoFocus)
        sld.setRange(1, OVER_CAPACITY)
        sld.setValue(75)
        sld.setGeometry(30, 40, 150, 30)

        self.c = Communicate()        
        self.wid = BurningWidget()
        self.c.updateBW[int].connect(self.wid.setValue)

        sld.valueChanged[int].connect(self.changeValue)
        hbox = QHBoxLayout()
        hbox.addWidget(self.wid)
        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addLayout(hbox)
        self.setLayout(vbox)

        self.setGeometry(300, 300, 390, 210)
        self.setWindowTitle('Burning widget')
        self.show()

    def changeValue(self, value):

        self.c.updateBW.emit(value)        
        self.wid.repaint()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

在我们的示例中,我们有一个QSlider和一个自定义小部件。 滑块控制自定义窗口小部件。 此小部件以图形方式显示了介质的总容量和可供我们使用的可用空间。 我们的自定义窗口小部件的最小值是 1,最大值是OVER_CAPACITY。 如果达到值MAX_CAPACITY,我们将开始绘制红色。 这通常表示过度燃烧。

刻录小部件位于窗口的底部。 这可以通过使用一个QHBoxLayout和一个QVBoxLayout来实现。

class BurningWidget(QWidget):

    def __init__(self):      
        super().__init__()        

它基于QWidget小部件的刻录小部件。

self.setMinimumSize(1, 30)

我们更改小部件的最小大小(高度)。 默认值对我们来说有点小。

font = QFont('Serif', 7, QFont.Light)
qp.setFont(font)

我们使用的字体比默认字体小。 这更适合我们的需求。

size = self.size()
w = size.width()
h = size.height()

step = int(round(w / 10))

till = int(((w / OVER_CAPACITY) * self.value))
full = int(((w / OVER_CAPACITY) * MAX_CAPACITY))

我们动态绘制小部件。 窗口越大,刻录的窗口小部件越大,反之亦然。 这就是为什么我们必须计算在其上绘制自定义窗口小部件的窗口小部件的大小的原因。 till参数确定要绘制的总大小。 该值来自滑块小部件。 它占整个面积的一部分。 full参数确定我们开始用红色绘制的点。

实际图纸包括三个步骤。 我们绘制黄色或红色和黄色矩形。 然后,我们绘制垂直线,将小部件分为几个部分。 最后,我们画出表示介质容量的数字。

metrics = qp.fontMetrics()
fw = metrics.width(str(self.num[j]))
qp.drawText(i-fw/2, h/2, str(self.num[j]))

我们使用字体指标来绘制文本。 我们必须知道文本的宽度,以便使其围绕垂直线居中。

def changeValue(self, value):

    self.c.updateBW.emit(value)        
    self.wid.repaint()

当我们移动滑块时,将调用changeValue()方法。 在方法内部,我们发送带有参数的自定义updateBW信号。 该参数是滑块的当前值。 该值随后用于计算刻录小部件的容量。 然后将自定义窗口小部件重新粉刷。

图:刻录小部件

在 PyQt5 教程的这一部分中,我们创建了一个自定义小部件。

{% raw %}

Qyoto 中的小部件

原文: http://zetcode/gui/vbqyoto/widgets/

在 Visual Basic Qyoto 编程教程的这一部分中,我们将介绍 Qyoto 小部件。

小部件是 GUI 应用的基本构建块。 多年来,几个小部件已成为所有 OS 平台上所有工具包中的标准。 例如,按钮,复选框或滚动条。 Qyoto 有一组丰富的小部件,可以满足大多数编程需求。 可以将更多专门的窗口小部件创建为自定义窗口小部件。

QCheckBox

QCheckBox是具有两种状态的窗口小部件:开和关。 开状态通过复选标记显示。 它用来表示一些布尔属性。 QCheckBox小部件提供一个带有文本标签的复选框。

' ZetCode Mono Visual Basic Qt tutorial

' This program toggles the title of the
' window with the QCheckBox widget
'
' author jan bodnar
' last modified April 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Public Sub New()

        Me.SetWindowTitle("QCheckBox")

        Me.InitUI()

        Me.Resize(250, 200)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        Dim cb As New QCheckBox("Show title", Me)
        cb.Move(50, 50)
        cb.SetCheckState(True)
        Connect(cb, SIGNAL("clicked(bool)"), Me, SLOT("OnToggle(bool)"))

    End Sub

    <Q_SLOT()> _
    Private Sub OnToggle(ByVal state As Boolean)

        If state
             Me.SetWindowTitle("QCheckBox")
        Else
             Me.SetWindowTitle("")
        End If

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在我们的示例中,我们在窗口上放置了一个复选框。 复选框显示/隐藏窗口的标题。

Me.SetWindowTitle("QCheckBox")

在构建窗口期间,我们为窗口设置标题。

Dim cb As New QCheckBox("Show title", Me)

QCheckBox小部件已创建。 构造器的第一个参数是其文本标签。 第二个参数是父窗口小部件。

cb.SetCheckState(True)

标题在应用的开始处可见。 因此,也必须选中该复选框。 我们使用SetCheckState()方法来选中该复选框。

Connect(cb, SIGNAL("clicked(bool)"), Me, SLOT("OnToggle(bool)"))

当我们单击复选框时,将发出clicked(bool)信号。 发出信号时,我们触发OnToggle()方法。

<Q_SLOT()> _
Private Sub OnToggle(ByVal state As Boolean)
...
End Sub

方法定义之前带有Q_SLOT()属性。 此属性通知编译器有关自定义槽的信息。

If state
    Me.SetWindowTitle("QCheckBox")
Else
    Me.SetWindowTitle("")
End If

根据复选框的状态,我们显示或隐藏窗口的标题。

图:QCheckBox

QLabel

QLabel小部件用于显示文本或图像。 没有用户交互。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program shows lyrics on the
' window
'
' author jan bodnar
' last modified April 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Public Sub New()

        Me.SetWindowTitle("You know I'm no Good")

        Me.InitUI()

        Me.Resize(250, 200)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        Dim text As String
        text = "Meet you downstairs in the bar and heard" + vbNewLine + _
"your rolled up sleeves and your skull t-shirt" + vbNewLine + _
"You say why did you do it with him today?" + vbNewLine + _
"and sniff me out like I was Tanqueray" + vbNewLine + _
"" + vbNewLine + _
"cause you're my fella, my guy" + vbNewLine + _
"hand me your stella and fly" + vbNewLine + _
"by the time I'm out the door" + vbNewLine + _
"you tear men down like Roger Moore" + vbNewLine + _
"" + vbNewLine + _
"I cheated myself" + vbNewLine + _
"like I knew I would" + vbNewLine + _
"I told ya, I was trouble" + vbNewLine + _
"you know that I'm no good" 

        Dim label As New QLabel(text, Me)
        label.Font = New QFont("Purisa", 9)

        Dim vbox As New QVBoxLayout()
        vbox.AddWidget(label)
        SetLayout(vbox)

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

我们的示例在窗口中显示了歌曲的歌词。

Dim text As String
text = "Meet you downstairs in the bar and heard" + vbNewLine + _
"your rolled up sleeves and your skull t-shirt" + vbNewLine + _
...

我们定义了多行文字。 与 C# ,Python 或 Ruby 不同,没有简单的结构可以用 Visual Basic 语言创建多行文本。 若要在 Visual Basic 中创建多行文本,我们使用vbNewLine打印常量,+连接字符和_行终止字符。

Dim label As New QLabel(text, Me)
label.Font = New QFont("Purisa", 9)

我们创建标签小部件并更改其字体。

Dim vbox As New QVBoxLayout()
vbox.AddWidget(label)
SetLayout(vbox)

代替手动编码标签的位置和大小,我们将标签放入盒子布局中。

图:QLabel

QLineEdit

QLineEdit是一个小部件,允许输入和编辑单行纯文本。 QLineEdit小部件具有撤消/重做,剪切/粘贴和拖放功能。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program demonstrates the 
' QLineEdit widget. Text entered in the QLineEdit
' widget is shown in a QLabel widget.
'
' author jan bodnar
' last modified April 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Dim label As QLabel

    Public Sub New()

        Me.InitUI()

        Me.SetWindowTitle("QLineEdit")
        Me.Resize(250, 200)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        label = New QLabel(Me)

        Dim edit As New QLineEdit(Me)
        Connect(edit, SIGNAL("textChanged(QString)"), Me, _
            SLOT("OnChanged(QString)"))

        edit.Move(60, 100)
        label.Move(60, 40)

    End Sub

    <Q_SLOT()> _
    Private Sub OnChanged(ByVal text As String)

        label.SetText(text)
        label.AdjustSize()

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在我们的示例中,我们显示了两个小部件。 行编辑和标签小部件。 输入到行编辑中的文本显示在标签窗口小部件中。

Dim edit As New QLineEdit(Me)

QLineEdit小部件已创建。

Connect(edit, SIGNAL("textChanged(QString)"), Me, _
    SLOT("OnChanged(QString)"))

当我们在行编辑中键入或删除某些文本时,将触发OnChanged()方法。 该方法采用字符串参数。

<Q_SLOT()> _
Private Sub OnChanged(ByVal text As String)

    label.SetText(text)
    label.AdjustSize()

End Sub

OnChanged()方法中,我们将行编辑的内容设置为标签窗口小部件。 AdjustSize()方法确保所有文本都是可见的。

图:QLineEdit小部件

ToggleButton

切换按钮是设置了可检查标志的按钮。 切换按钮是具有两种状态的按钮。 已按下但未按下。 通过单击可以在这两种状态之间切换。 在某些情况下此功能非常合适。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program uses toggle buttons to 
' change the background color of
' a widget
'
' author jan bodnar
' last modified April 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Dim square As QWidget
    Dim color As QColor

    Dim redb As QPushButton
    Dim greenb As QPushButton
    Dim blueb As QPushButton

    Public Sub New()

        Me.InitUI()

        Me.SetWindowTitle("Toggle buttons")
        Me.Resize(350, 240)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        color = New QColor()

        redb = New QPushButton("Red", Me)
        redb.Checkable = True
        greenb = New QPushButton("Green", Me)
        greenb.Checkable = True
        blueb = New QPushButton("Blue", Me)
        blueb.Checkable = True

        Connect(redb, SIGNAL("toggled(bool)"), Me, SLOT("OnToggled()"))
        Connect(greenb, SIGNAL("toggled(bool)"), Me, SLOT("OnToggled()"))
        Connect(blueb, SIGNAL("toggled(bool)"), Me, SLOT("OnToggled()"))

        square = New QWidget(Me)
        square.SetStyleSheet("QWidget { background-color: black }")

        redb.Move(30, 30)
        greenb.Move(30, 80)
        blueb.Move(30, 130)
        square.SetGeometry(150, 25, 150, 150)

    End Sub

    <Q_SLOT()> _
    Private Sub OnToggled()

        Dim red As Integer = color.Red()
        Dim green As Integer = color.Green()
        Dim blue As Integer = color.Blue()

        If redb.Checked 
            red = 255
        Else 
            red = 0
        End If

        If greenb.Checked
            green = 255
        Else 
            green = 0
        End If

        If blueb.Checked
            blue = 255
        Else 
            blue = 0
        End If

        color = New QColor(red, green, blue)

        Dim sheet As String = String.Format("QWidget {{ background-color: {0} }}", _
            color.Name())
        square.SetStyleSheet(sheet)

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在代码示例中,我们使用三个切换按钮来更改矩形小部件的颜色。

Dim square As QWidget
Dim color As QColor

Dim redb As QPushButton
Dim greenb As QPushButton
Dim blueb As QPushButton

我们定义了五个对象。 正方形小部件是QWidget,它显示颜色。 color变量用于保存颜色值。 这三个按钮是切换按钮,用于混合颜色值。

redb = New QPushButton("Red", Me)
redb.Checkable = True

我们创建一个QPushButton小部件。 Checkable属性将按钮更改为切换按钮。

Connect(redb, SIGNAL("toggled(bool)"), Me, SLOT("OnToggled()"))
Connect(greenb, SIGNAL("toggled(bool)"), Me, SLOT("OnToggled()"))
Connect(blueb, SIGNAL("toggled(bool)"), Me, SLOT("OnToggled()"))

所有三个按钮都插入到一个方法调用中,即OnToggled()方法。

square = New QWidget(Me)
square.SetStyleSheet("QWidget { background-color: black }")

我们创建方形小部件。 一开始是黑色的。 在 Qyoto 中,我们使用样式表来自定义小部件的外观。

OnToggled()方法内部,我们确定颜色值并将正方形小部件更新为新颜色。

Dim red As Integer = color.Red()
Dim green As Integer = color.Green()
Dim blue As Integer = color.Blue()

在这里,我们确定方形小部件的当前颜色。

If redb.Checked 
    red = 255
Else 
    red = 0
End If

根据红色切换按钮的状态,更改颜色的红色部分。

color = New QColor(red, green, blue)

我们创建一个新的颜色值。

Dim sheet As String = String.Format("QWidget {{ background-color: {0} }}", _
    color.Name())

我们使用 Visual Basic 格式对象创建适当的样式表。

square.SetStyleSheet(sheet)

正方形的颜色已更新。

图:开关按钮

QComboBox

QComboBox是一个小部件,允许用户从选项列表中进行选择。 这是一个显示当前项目的选择小部件,可以弹出可选择项目的列表。 组合框可能是可编辑的。 它以占用最少屏幕空间的方式向用户显示选项列表。

' ZetCode Mono Visual Basic Qt tutorial
'
' In this program, we use the QComboBox
' widget to select an option. 
' The selected option is shown in the
' QLabel widget
'
' author jan bodnar
' last modified April 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Dim label As QLabel

    Public Sub New()

        Me.SetWindowTitle("QComboBox")

        Me.InitUI()

        Me.Resize(250, 200)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        label = New QLabel("Ubuntu", Me)

        Dim combo As New QComboBox(Me)
        combo.AddItem("Ubuntu")
        combo.AddItem("Mandriva")
        combo.AddItem("Fedora")
        combo.AddItem("Red Hat")
        combo.AddItem("Gentoo")

        combo.Move(50, 30)
        label.Move(50, 100)

        Connect(combo, SIGNAL("activated(QString)"), _
                 Me, SLOT("OnActivated(QString)"))

    End Sub

    <Q_SLOT()> _
    Private Sub OnActivated(ByVal text As String)

        label.SetText(text)
        label.AdjustSize()

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在我们的代码示例中,我们有两个小部件。 组合框和标签小部件。 从组合框中选择的选项显示在标签中。

label = New QLabel("Ubuntu", Me)

这是一个标签,它将显示组合框中当前选择的选项。

Dim combo As New QComboBox(Me)

我们创建QComboBox小部件的实例。

combo.AddItem("Ubuntu")
combo.AddItem("Mandriva")
combo.AddItem("Fedora")
combo.AddItem("Red Hat")
combo.AddItem("Gentoo")

组合框将填充值。

Connect(combo, SIGNAL("activated(QString)"), _
          Me, SLOT("OnActivated(QString)"))

当我们从组合框中选择一个选项时,将触发OnActivated()方法。

<Q_SLOT()> _
Private Sub OnActivated(ByVal text As String)

    label.SetText(text)
    label.AdjustSize()

End Sub

OnActivated()方法中,我们将标签小部件更新为从组合框中选择的当前字符串。

图:QComboBox小部件

在 Visual Basic Qyoto 教程的这一部分中,我们介绍了几个 Qyoto 小部件。

{% endraw %}

Qyoto 中的菜单和工具栏

原文: http://zetcode/gui/vbqyoto/menustoolbars/

在 Visual Basic Qyoto 编程教程的这一部分中,我们将使用菜单和工具栏。

菜单栏是 GUI 应用中最可见的部分之一。 它是位于各个菜单中的一组命令。 在控制台应用中,您必须记住所有这些神秘命令,在这里,我们将大多数命令分组为逻辑部分。 有公认的标准可以进一步减少学习新应用的时间。 菜单将我们可以在应用中使用的命令分组。 使用工具栏可以快速访问最常用的命令。

简单菜单

第一个示例将显示一个简单的菜单。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program shows a simple
' menu. It has one action, which
' will terminate the program, when
' selected. 
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QMainWindow

    Public Sub New()

        Me.SetWindowTitle("Simple menu")

        Me.InitUI()

        Me.Resize(250, 200)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        Dim quit As New QAction("&Quit", Me)

        Dim file As QMenu = Me.MenuBar().AddMenu("&File")
        file.AddAction(quit)

        Connect(quit, SIGNAL("triggered()"), qApp, SLOT("quit()"))

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app as New VBQApp
        QApplication.Exec()
    End Sub

End Class

我们有一个菜单栏,一个菜单和一个动作。 为了使用菜单,我们必须继承QMainWindow小部件。

Dim quit As New QAction("&Quit", Me)

此代码行创建一个QAction。 每个QMenu具有一个或多个动作对象。 注意 AND 字符(&)。 它为以下项目创建快捷方式: Alt + Q 。 它还强调了Q字符。 下拉菜单中的文件时,该快捷方式处于活动状态。

Dim file As QMenu = Me.MenuBar().AddMenu("&File")
file.AddAction(quit)

我们创建一个QMenu对象。 &字符创建快捷方式: Alt + F 。 连续的快捷键 Alt + FAlt + Q 退出了应用。

Connect(quit, SIGNAL("triggered()"), qApp, SLOT("quit()"))

当我们从菜单中选择此选项时,应用退出。

图:简单菜单

创建一个子菜单

子菜单是插入另一个菜单对象的菜单。 下一个示例对此进行了演示。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program creates 
' a submenu
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QMainWindow

    Public Sub New()

        Me.SetWindowTitle("Submenu")

        Me.InitUI()

        Me.Resize(280, 200)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        Dim quit As New QAction("&Quit", Me)

        Dim file As QMenu = MenuBar().AddMenu("&File")
        Dim impm As New QMenu("Import")

        Dim seeds As New QAction("Import news feed...", Me)
        Dim marks As New QAction("Import bookmarks...", Me)
        Dim mail As New QAction("Import mail...", Me)

        impm.AddAction(seeds)
        impm.AddAction(marks)
        impm.AddAction(mail)

        file.AddMenu(impm)
        file.AddAction(quit)

        Connect(quit, SIGNAL("triggered()"), qApp, SLOT("quit()"))

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在示例中,文件菜单的子菜单中有三个选项。

Dim file As QMenu = MenuBar().AddMenu("&File")
Dim impm As New QMenu("Import")

我们有两个QMenu对象。 文件菜单和导入菜单。

Dim seeds As New QAction("Import news feed...", Me)
Dim marks As New QAction("Import bookmarks...", Me)
Dim mail As New QAction("Import mail...", Me)

我们创建三个动作对象。

impm.AddAction(seeds)
impm.AddAction(marks)
impm.AddAction(mail)

我们将动作对象添加到导入菜单中。

file.AddMenu(impm)

最后,我们将导入菜单添加到文件菜单中。

图:子菜单

图像,菜单,分隔符

在以下示例中,我们将进一步增强以前的应用。 我们将在菜单中添加图标,使用快捷方式和分隔符。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program shows image
' menu items, a shorcut and a separator
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QMainWindow

    Public Sub New()

        Me.SetWindowTitle("Image menu")

        Me.InitUI()

        Me.Resize(280, 200)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        Dim newpix As New QIcon("new.png")
        Dim openpix As New QIcon("open.png")
        Dim quitpix As New QIcon("quit.png")

        Dim newa As New QAction(newpix, "&New", Me)
        Dim open As New QAction(openpix, "&Open", Me)
        Dim quit As New QAction(quitpix, "&Quit", Me)

        quit.Shortcut = New QKeySequence("Ctrl+Q")    

        Dim file As QMenu = MenuBar().AddMenu("&File")
        file.AddAction(newa)
        file.AddAction(open)
        file.AddSeparator()
        file.AddAction(quit)

        Connect(quit, SIGNAL("triggered()"), qApp, SLOT("quit()"))

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在我们的示例中,我们有一个包含三个动作的菜单。 如果我们选择退出操作,则实际上只有退出操作才可以执行某些操作。 我们还创建了分隔符和 Ctrl + Q 快捷方式,它们将终止应用。

Dim newpix As New QIcon("new.png")
Dim openpix As New QIcon("open.png")
Dim quitpix As New QIcon("quit.png")

这些是我们将在应用中使用的 PNG 图像。

Dim newa As New QAction(newpix, "&New", Me)
Dim open As New QAction(openpix, "&Open", Me)
Dim quit As New QAction(quitpix, "&Quit", Me)

在这里,我们创建三个动作对象。 第一个参数是QIcon

quit.Shortcut = New QKeySequence("Ctrl+Q") 

这行创建一个快捷方式。 通过按下此快捷方式,我们将运行退出操作,这将终止应用。

file.AddSeparator()

我们创建一个分隔符。 分隔符是一条水平线,它使我们能够将菜单操作分组为一些逻辑部分。

图:图像 s, shortcut and a separator

工具栏

QToolBar类提供了一个可移动面板,其中包含一组控件,这些控件提供对应用操作的快速访问。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program creates a 
' toolbar
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QMainWindow

    Public Sub New()

        Me.SetWindowTitle("Toolbar")

        Me.InitUI()

        Me.Resize(280, 200)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        Dim newpi As New QIcon("new.png")
        Dim openpi As New QIcon("open.png")
        Dim quitpi As New QIcon("quit.png")

        Dim toolbar As QToolBar = AddToolBar("main toolbar")
        toolbar.AddAction(newpi, "New File")
        toolbar.AddAction(openpi, "Open File")
        toolbar.AddSeparator()
        Dim quit As QAction = toolbar.AddAction(quitpi, _
            "Quit Application")

        Connect(quit, SIGNAL("triggered()"), qApp, SLOT("quit()"))

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app as New VBQApp
        QApplication.Exec()
    End Sub

End Class

我们创建一个带有三个动作对象和一个分隔符的工具栏。

Dim newpi As New QIcon("new.png")
Dim openpi As New QIcon("open.png")
Dim quitpi As New QIcon("quit.png")

工具栏动作对象将显示这些图标。

Dim toolbar As QToolBar = AddToolBar("main toolbar")

QMainWindow类的AddToolBar()方法为应用创建一个工具栏。 文本字符串为工具栏命名。 此名称用于引用此工具栏,因为一个应用中可以有多个工具栏。 如果右键单击窗口区域,我们将看到一个可检查的选项,该选项显示/隐藏工具栏。

toolbar.AddSeparator()

我们创建一个垂直分隔符。

Connect(quit, SIGNAL("triggered()"), qApp, SLOT("quit()"))

当我们单击退出操作对象时,应用终止。

图:工具栏

撤销重做

以下示例演示了如何停用工具栏上的工具栏按钮。 这是 GUI 编程中的常见做法。 例如,保存按钮。 如果我们将文档的所有更改都保存到磁盘上,则在大多数文本编辑器中,“保存”按钮将被停用。 这样,应用会向用户指示所有更改都已保存。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program disables/enables
' toolbuttons on a toolbar
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QMainWindow

    Dim clicks As Integer = 0
    Dim undoButton As QToolButton
    Dim redoButton As QToolButton

    Public Sub New()

        Me.SetWindowTitle("Undo redo")

        Me.InitUI()

        Me.Resize(280, 200)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        Dim undoi As New QIcon("undo.png")
        Dim redoi As New QIcon("redo.png")
        Dim quitpi As New QIcon("quit.png")

        Dim toolbar As New QToolBar
        undoButton = New QToolButton
        redoButton = New QToolButton

        Dim undoAction As New QAction(undoi, "Undo", undoButton)
        Dim redoAction As New QAction(redoi, "Redo", redoButton)

        undoButton.SetDefaultAction(undoAction)
        redoButton.SetDefaultAction(redoAction)

        toolbar.AddSeparator()
        toolbar.AddWidget(undoButton)
        toolbar.AddWidget(redoButton)

        Dim quit As QAction = toolbar.AddAction(quitpi, "Quit Application")

        Connect(quit, SIGNAL("triggered()"), qApp, SLOT("quit()"))

        Connect(undoButton, SIGNAL("triggered(QAction*)"), _
            Me, SLOT("Count(QAction*)"))
        Connect(redoButton, SIGNAL("triggered(QAction*)"), _
            Me, SLOT("Count(QAction*)"))

        AddToolBar(toolbar)

    End Sub

    <Q_SLOT()> _
    Private Sub Count(ByVal action As QAction)

        If "Undo".Equals(action.Text)
            clicks -= 1
        Else 
            clicks += 1
        End If

        If clicks <= 0 
            undoButton.SetDisabled(True)
            redoButton.SetDisabled(False)
        End If

        If clicks >= 5 
            undoButton.SetDisabled(False)
            redoButton.SetDisabled(True)
        End If

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在我们的示例中,我们有三个QAction对象和一个分隔符。 在撤消或重做按钮上单击几下后,它们将被停用。 外观上,按钮显示为灰色。

Dim clicks As Integer = 0

clicks变量确定哪个按钮被激活或停用。

Connect(undoButton, SIGNAL("triggered(QAction*)"), _
    Me, SLOT("Count(QAction*)"))
Connect(redoButton, SIGNAL("triggered(QAction*)"), _
    Me, SLOT("Count(QAction*)"))

单击工具栏按钮,将发射triggered()信号。 我们将此信号连接到Count()方法。 它接收触发它的QAction对象。

If "Undo".Equals(action.Text)
    clicks -= 1
Else 
    clicks += 1
End If

撤消工具栏按钮从clicks变量中减去 1。 重做添加 1。根据clicks变量的值,我们启用/禁用工具栏按钮。

If clicks <= 0 
    undoButton.SetDisabled(True)
    redoButton.SetDisabled(False)
End If

SetDisabled()方法激活或停用工具栏按钮。

图:撤销和重做

在 Visual Basic Qyoto 教程的这一部分中,我们提到了菜单和工具栏。

{% raw %}

Qyoto 对话框

原文: http://zetcode/gui/vbqyoto/dialogs/

在 Visual Basic Qyoto 编程教程的这一部分中,我们将使用对话框。

对话框窗口或对话框是大多数现代 GUI 应用必不可少的部分。 对话被定义为两个或更多人之间的对话。 在计算机应用中,对话框是一个窗口,用于与应用“对话”。 对话框用于输入数据,修改数据,更改应用设置等。对话框是用户与计算机程序之间进行通信的重要手段。

MessageDialog

消息框是方便的对话框,可向应用的用户提供消息。 该消息由文本和图像数据组成。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program shows
' QMessageBox dialogs
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Public Sub New()

        Me.SetWindowTitle("Message boxes")

        Me.InitUI()

        Me.Resize(220, 90)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        Dim grid As New QGridLayout(Me)
        grid.Spacing = 2

        Dim errb As New QPushButton("Error", Me)
        Dim warnb As New QPushButton("Warning", Me)
        Dim questb As New QPushButton("Question", Me)
        Dim infob As New QPushButton("Information", Me)
        Dim aboutb As New QPushButton("About", Me)

        grid.AddWidget(errb, 0, 0)
        grid.AddWidget(warnb, 0, 1)
        grid.AddWidget(questb, 1, 0)
        grid.AddWidget(infob, 1, 1)
        grid.AddWidget(aboutb, 2, 0)

        Connect(errb, SIGNAL("clicked()"), Me, SLOT("OnClicked()"))
        Connect(warnb, SIGNAL("clicked()"), Me, SLOT("OnClicked()"))
        Connect(questb, SIGNAL("clicked()"), Me, SLOT("OnClicked()"))
        Connect(infob, SIGNAL("clicked()"), Me, SLOT("OnClicked()"))
        Connect(aboutb, SIGNAL("clicked()"), Me, SLOT("OnClicked()"))

    End Sub

    <Q_SLOT()> _
    Private Sub OnClicked()

        Dim button As QPushButton = Sender()

        If "Error".Equals(button.Text())
            QMessageBox.critical(Me, "Error", "Error loading file!")
        Else If "Warning".Equals(button.Text())
            QMessageBox.warning(Me, "Warning", "Operation not permitted!")
        Else If "Question".Equals(button.Text())
            QMessageBox.question(Me, "Question", "Are you sure to quit?")
        Else If "Information".Equals(button.Text())
            QMessageBox.information(Me, "Information", "Download completed.")
        Else If "About".Equals(button.Text())
            QMessageBox.about(Me, "About", "ZetCode Qyoto Visual Basic tutorial.")        
        End If

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

我们使用GridLayout管理器来设置五个按钮的网格。 每个按钮显示一个不同的消息框。

Dim button As QPushButton = Sender()

在这里,我们确定哪个按钮称为ShowDialog()方法。

If "Error".Equals(button.Text())
    QMessageBox.critical(Me, "Error", "Error loading file!")

如果按下错误按钮,则会显示错误对话框。 我们使用QMessageBox类的静态方法来显示消息框。

QInputDialog

QInputDialog类提供了一个简单的便捷对话框,可从用户那里获取单个值。 输入值可以是字符串,数字或列表中的项目。 必须设置标签以告知用户他们应该输入什么。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program shows
' QInputDialog dialogs
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Dim edit As QLineEdit

    Public Sub New()

        Me.SetWindowTitle("QInputDialog")

        Me.InitUI()

        Me.Resize(300, 150)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        Dim show As New QPushButton("Dialog", Me)

        Connect(show, SIGNAL("clicked()"), Me, SLOT("ShowDialog()"))

        show.FocusPolicy = FocusPolicy.NoFocus
        show.Move(20, 20)

        edit = New QLineEdit(Me)
        edit.Move(130, 22)

    End Sub

    <Q_SLOT()> _
    Private Sub ShowDialog()

        Dim text As String = QInputDialog.GetText( _
                Me, "Input Dialog", "Enter your name")

        If text <> Nothing AndAlso text.Trim() <> String.Empty
            edit.SetText(text)
        End If

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在代码示例中,我们有一个按钮和一行编辑。 该按钮显示一个输入对话框。 我们得到一些文本,文本显示在行编辑小部件中。

Dim text As String = QInputDialog.GetText( _
        Me, "Input Dialog", "Enter your name")

GetText()静态方法创建输入对话框。 对话框中的文本存储在text变量中。

If text <> Nothing AndAlso text.Trim() <> String.Empty
    edit.SetText(text)
End If

在更新行编辑之前,请确保text变量不为null且不为空,并且不仅由空格组成。

图:输入对话框

QColorDialog

QColorDialog类提供用于指定颜色的对话框小部件。 颜色对话框的功能是允许用户选择颜色。

' ZetCode Mono Visual Basic Qt tutorial
'
' In this program, we use the
' QColorDialog to change the color
' of a label text
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Dim label As QLabel

    Public Sub New()

        Me.SetWindowTitle("QColorDialog")

        Me.InitUI()

        Me.Resize(300, 150)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        label = New QLabel("ZetCode Qyoto Visual Basic tutorial", Me)

        Dim vbox As New QVBoxLayout(Me)
        label.Alignment = AlignmentFlag.AlignCenter
        vbox.AddWidget(label)

    End Sub

    Protected Overrides Sub MousePressEvent(ByVal e As QMouseEvent)

        Dim color As QColor = QColorDialog.GetColor()

        If Not color.IsValid() Then
            Return
        End If

        Dim style As String = String.Format("QWidget {{ color: {0} }}", _
            color.Name())
        label.SetStyleSheet(style)

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

我们在窗口中心显示一些文本。 通过单击窗口区域,我们显示一个颜色对话框。 我们将文本前景色更改为从对话框中选择的颜色。

Protected Overrides Sub MousePressEvent(ByVal e As QMouseEvent)
    ...
End Sub

为了接收我们窗口的鼠标按下事件,我们必须重写MousePressEvent()方法。

Dim color As QColor = QColorDialog.GetColor()

正在创建QColorDialog。 所选颜色存储在color变量中。

If Not color.IsValid() Then
    Return
End If

当按下取消按钮时,我们什么也不做。

Dim style As String = String.Format("QWidget {{ color: {0} }}", _
    color.Name())
label.SetStyleSheet(style)

在这里,我们更新标签文本的前景色。

图:QColorDialog

QFontDialog

QFontDialog类提供用于选择字体的对话框小部件。

' ZetCode Mono Visual Basic Qt tutorial
'
' In this program, we use the
' QFontDialog to change the font
' of a label text
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Dim label As QLabel

    Public Sub New()

        Me.SetWindowTitle("QFontDialog")

        Me.InitUI()

        Me.Resize(300, 150)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Private Sub InitUI()

        label = New QLabel("ZetCode Qyoto Visual Basic tutorial", Me)

        Dim vbox As New QVBoxLayout(Me)
        label.Alignment = AlignmentFlag.AlignCenter
        vbox.AddWidget(label)

    End Sub

    Protected Overrides Sub MousePressEvent(ByVal e As QMouseEvent)

        Dim ok As Boolean = True

        Dim font As QFont = QFontDialog.GetFont(ok)

        If Not ok Then
            Return
        End If

        label.Font = font

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

此示例与上一个示例相似。 这次,我们更改文本的字体。

Dim font As QFont = QFontDialog.GetFont(ok)

正在创建QFontDialog。 当我们按下对话框的 OK 按钮时,将设置boolean ok变量。

If Not ok Then
    Return
End If

如果没有按下“确定”按钮,我们什么也不做。

label.Font = font

font字段存储所选字体。 我们将标签的字体更新为新选择的字体。

图:QFontDialog

在 Visual Basic Qyoto 教程的这一部分中,我们使用了对话框窗口。

{% endraw %}

Qyoto 中的绘图

原文: http://zetcode/gui/vbqyoto/painting/

在 Visual Basic Qyoto 编程教程的这一部分中,我们将进行绘图。

我们什么时候需要油漆? 在某些情况下,当我们需要从头开始创建小部件时。 在这种情况下,我们需要绘图。 或者我们想创建图表,特殊装饰,效果或小部件增强。

当我们在 Qyoto 库中进行绘图时,QPainter类非常有用。 绘图事件通过PaintEvent()方法接收。 若要进行自定义绘图,我们必须重新实现此方法。

图案

在《京都议定书》中,我们可以使用各种图案来填充形状的内部。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program draws nine rectangles.
' The interiors are filled with
' different built-in patterns.
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Public Sub New()

        Me.SetWindowTitle("Patterns")

        Me.Resize(350, 280)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Protected Overrides Sub PaintEvent(ByVal e As QPaintEvent)

        Dim painter As New QPainter(Me)
        Me.DrawPatterns(painter)

        painter.End()

    End Sub

    Private Sub DrawPatterns(ByRef painter As QPainter)

        painter.SetPen(PenStyle.NoPen)

        painter.SetBrush(Qt.BrushStyle.HorPattern)
        painter.DrawRect(10, 15, 90, 60)

        painter.SetBrush(Qt.BrushStyle.VerPattern)
        painter.DrawRect(130, 15, 90, 60)

        painter.SetBrush(Qt.BrushStyle.CrossPattern)
        painter.DrawRect(250, 15, 90, 60)

        painter.SetBrush(Qt.BrushStyle.Dense7Pattern)
        painter.DrawRect(10, 105, 90, 60)

        painter.SetBrush(Qt.BrushStyle.Dense6Pattern)
        painter.DrawRect(130, 105, 90, 60)

        painter.SetBrush(Qt.BrushStyle.Dense5Pattern)
        painter.DrawRect(250, 105, 90, 60)

        painter.SetBrush(Qt.BrushStyle.BDiagPattern)
        painter.DrawRect(10, 195, 90, 60)

        painter.SetBrush(Qt.BrushStyle.FDiagPattern)
        painter.DrawRect(130, 195, 90, 60)

        painter.SetBrush(Qt.BrushStyle.DiagCrossPattern)
        painter.DrawRect(250, 195, 90, 60)

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在代码示例中,我们将绘制九个矩形,并用不同的画笔图案填充它们。

Protected Overrides Sub PaintEvent(ByVal e As QPaintEvent)

    Dim painter As New QPainter(Me)
    Me.DrawPatterns(painter)

    painter.End()

End Sub

当需要重绘窗口区域时,将调用PaintEvent()方法。 当我们调整窗口大小,最大化或最小化窗口时,就会发生这种情况。在此方法中,我们创建了QPainter对象。 该对象用于完成 Qyoto 中的所有绘图。 绘图本身被委托给DrawPatterns()方法。 End()方法释放绘图时使用的资源。

painter.SetPen(PenStyle.NoPen)

笔对象用于绘制形状的轮廓。 在我们的示例中,我们将不使用笔。

painter.SetBrush(Qt.BrushStyle.HorPattern)

我们将水平图案设置为画笔。 画笔用于绘制形状的内部。

painter.DrawRect(10, 15, 90, 60)

我们使用当前的笔和画笔绘制一个矩形。 该方法的前两个参数是 x,y 坐标。 最后两个参数是矩形的宽度和高度。

图:图案

形状

Qyoto 绘图 API 可以绘制各种形状。 以下编程代码示例将显示其中的一些。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program draws basic shapes
' available in Qyoto.
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Public Sub New()

        Me.SetWindowTitle("Shapes")

        Me.Resize(350, 280)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Protected Overrides Sub PaintEvent(ByVal e As QPaintEvent)

        Dim painter As New QPainter(Me)
        Me.DrawShapes(painter)

        painter.End()

    End Sub

    Private Sub DrawShapes(ByRef painter As QPainter)

        painter.SetRenderHint(QPainter.RenderHint.Antialiasing)
        painter.SetPen(New QPen(New QBrush(New QColor("Gray")), 1))
        painter.SetBrush(New QBrush(New QColor("Gray")))

        Dim path1 As New QPainterPath()

        path1.MoveTo(5, 5)
        path1.CubicTo(40, 5,  50, 50,  99, 99)
        path1.CubicTo(5, 99,  50, 50,  5, 5)
        painter.DrawPath(path1)

        painter.DrawPie(130, 20, 90, 60, 30*16, 120*16)
        painter.DrawChord(240, 30, 90, 60, 0, 16*180)
        painter.DrawRoundRect(20, 120, 80, 50)

        Dim polygon As New QPolygon(5)
        polygon.SetPoint(0, 130, 140)
        polygon.SetPoint(1, 180, 170)
        polygon.SetPoint(2, 180, 140)
        polygon.SetPoint(3, 220, 110)
        polygon.SetPoint(4, 140, 100)

        painter.DrawPolygon(polygon)
        painter.DrawRect(250, 110, 60, 60)

        Dim baseline As New QPointF(20, 250)
        Dim font As New QFont("Georgia", 55)
        Dim path2 As New QPainterPath()

        path2.AddText(baseline, font, "Q")
        painter.DrawPath(path2)

        painter.DrawEllipse(140, 200, 60, 60)
        painter.DrawEllipse(240, 200, 90, 60)

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在此代码示例中,我们在窗口上绘制了九种不同的形状。 复杂路径,饼图,和弦,圆角矩形,多边形,矩形,基于字符的形状,圆形和椭圆形。

painter.SetRenderHint(QPainter.RenderHint.Antialiasing)

我们在示例中使用抗锯齿。 抗锯齿形状看起来更好,但是绘制它们需要更多时间。

painter.SetPen(New QPen(New QBrush(New QColor("Gray")), 1))
painter.SetBrush(New QBrush(New QColor("Gray")))

我们使用深灰色的笔和画笔绘制形状。

Dim path1 As New QPainterPath()

path1.MoveTo(5, 5)
path1.CubicTo(40, 5,  50, 50,  99, 99)
path1.CubicTo(5, 99,  50, 50,  5, 5)
painter.DrawPath(path1)

使用QPainterPath对象创建第一个复杂形状。 QPainterPath类为绘图操作提供了一个容器。 画家路径是由许多图形构造块(例如矩形,椭圆形,直线和曲线)组成的对象。

painter.DrawPie(130, 20, 90, 60, 30*16, 120*16)
painter.DrawChord(240, 30, 90, 60, 0, 16*180)
painter.DrawRoundRect(20, 120, 80, 50)

这三行画出一个饼图,一个和弦和一个圆角矩形。

Dim polygon As New QPolygon(5)
polygon.SetPoint(0, 130, 140)
polygon.SetPoint(1, 180, 170)
polygon.SetPoint(2, 180, 140)
polygon.SetPoint(3, 220, 110)
polygon.SetPoint(4, 140, 100)

painter.DrawPolygon(polygon)

在这里,我们创建一个多边形。

Dim baseline As New QPointF(20, 250)
Dim font As New QFont("Georgia", 55)
Dim path2 As New QPainterPath()

path2.AddText(baseline, font, "Q")
painter.DrawPath(path2)

这些线创建基于字符的形状。

painter.DrawEllipse(140, 200, 60, 60)
painter.DrawEllipse(240, 200, 90, 60)

这两条线分别创建一个圆和一个椭圆。

图:形状

透明矩形

透明性是指能够透视材料的质量。 了解透明度的最简单方法是想象一块玻璃或水。 从技术上讲,光线可以穿过玻璃,这样我们就可以看到玻璃后面的物体。

在计算机图形学中,我们可以使用 alpha 合成来实现透明效果。 Alpha 合成是将图像与背景组合以创建部分透明外观的过程。 合成过程使用 Alpha 通道。 (wikipedia,answers)

' ZetCode Mono Visual Basic Qt tutorial
'
' This program draws ten
' rectangles with different
' levels of transparency
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Public Sub New()

        Me.SetWindowTitle("Transparent rectangles")

        Me.Resize(590, 90)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Protected Overrides Sub PaintEvent(ByVal e As QPaintEvent)

        Dim painter As New QPainter(Me)
        Me.DrawRectangles(painter)

        painter.End()

    End Sub

    Private Sub DrawRectangles(ByRef painter As QPainter)

        painter.SetPen(PenStyle.NoPen)

        For i As Integer = 1 To 10
            painter.SetBrush(New QBrush(New QColor(0, 0, 255, i*25)))
            painter.DrawRect(50*i, 20, 40, 40)
        Next

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在示例中,我们将绘制十个具有不同透明度级别的矩形。

painter.SetPen(PenStyle.NoPen)

我们不用笔。

For i As Integer = 1 To 10
    painter.SetBrush(New QBrush(New QColor(0, 0, 255, i*25)))
    painter.DrawRect(50*i, 20, 40, 40)
Next

QColor对象的最后一个参数是 alpha 透明度值。

图:透明矩形

甜甜圈形状

在下面的示例中,我们通过旋转一堆椭圆来创建复杂的形状。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program draws a donut
' shape
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Public Sub New()

        Me.SetWindowTitle("Donut")

        Me.Resize(350, 280)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Protected Overrides Sub PaintEvent(ByVal e As QPaintEvent)

        Dim painter As New QPainter(Me)
        Me.DrawDonut(painter)

        painter.End()

    End Sub

    Private Sub DrawDonut(ByRef painter As QPainter)

        Dim color As New QColor()
        color.SetNamedColor("#333333")

        Dim pen As New QPen(color)
        pen.setWidthF(0.5)
        painter.SetPen(pen)

        painter.SetRenderHint(QPainter.RenderHint.Antialiasing)

        Dim h As Integer = Me.Height()
        Dim w As Integer = Me.Width()

        painter.Translate(New QPoint(w/2, h/2))

        For rot As Integer = 1 To 360 Step 5
            painter.DrawEllipse(-125, -40, 250, 80)
            painter.Rotate(5)
        Next

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

在此示例中,我们创建一个甜甜圈。 形状类似于曲奇,因此得名“甜甜圈”。

Dim color As New QColor()
color.SetNamedColor("#333333")

我们可以使用十六进制表示法来创建颜色对象。

Dim h As Integer = Me.Height()
Dim w As Integer = Me.Width()

在这里,我们确定窗口的宽度和高度。

painter.Translate(New QPoint(w/2, h/2))

我们将坐标系移到窗口的中间。 这样,我们使绘图在数学上更容易。

For rot As Integer = 1 To 360 Step 5
    painter.DrawEllipse(-125, -40, 250, 80)
    painter.Rotate(5)
Next

我们绘制一个椭圆对象 72 次。 每次,我们将椭圆旋转 5 度。 这将创建我们的甜甜圈形状。

图:多纳圈

绘制文字

在最后一个示例中,我们将在窗口上绘制文本。

' ZetCode Mono Visual Basic Qt tutorial
'
' This program draws text
' on the window
'
' author jan bodnar
' last modified May 2009
' website www.zetcode

Imports Qyoto

Public Class VBQApp 
    Inherits QWidget

    Public Sub New()

        Me.SetWindowTitle("Unfaitful")

        Me.Resize(300, 280)
        Me.Move(300, 300)
        Me.Show()

    End Sub

    Protected Overrides Sub PaintEvent(ByVal e As QPaintEvent)

        Dim painter As New QPainter(Me)
        Me.DrawLyrics(painter)

        painter.End()

    End Sub

    Private Sub DrawLyrics(ByRef painter As QPainter)

        painter.SetBrush(New QBrush(new QColor(25, 25, 25)))
        painter.SetFont(New QFont("Purisa", 10))

        painter.DrawText(New QPoint(20, 30), _
                "I don't wanna do this anymore")
        painter.DrawText(New QPoint(20, 60), _
                "I don't wanna be the reason why")
        painter.DrawText(New QPoint(20, 90), _
                "Everytime I walk out the door")
        painter.DrawText(New QPoint(20, 120), _
                "I see him die a little more inside")
        painter.DrawText(New QPoint(20, 150), _
                "I don't wanna hurt him anymore")
        painter.DrawText(New QPoint(20, 180), _
                "I don't wanna take away his life")
        painter.DrawText(New QPoint(20, 210), _
                "I don't wanna be...") 
        painter.DrawText(New QPoint(20, 240), _
                "A murderer")

    End Sub

    Public Shared Sub Main(ByVal args() As String)
        Dim qapp As New QApplication(args)
        Dim app As New VBQApp
        QApplication.Exec()
    End Sub

End Class

我们在窗口上画一首歌歌词。

painter.SetFont(New QFont("Purisa", 10))

我们为文本设置了 Purisa 字体。

painter.DrawText(New QPoint(20, 30), _
        "I don't wanna do this anymore")

DrawText()方法用于绘制文本。

图:绘制文本

在 Visual Basic Qyoto 编程教程的这一部分中,我们做了一些绘图。

发布者:admin,转转请注明出处:http://www.yc00.com/web/1754948101a5219463.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信